regression compiles again, bad let*-spec
[CommonLispStat.git] / src / stat-models / regression.lisp
blob1effe383792632c34ba48cbdbeb37e0a2bd8fa2a
1 ;;; -*- mode: lisp -*-
2 ;;;
3 ;;; Copyright (c) 2008--, by A.J. Rossini <blindglobe@gmail.com>
4 ;;; See COPYRIGHT file for any additional restrictions (BSD license).
5 ;;; Since 1991, ANSI was finally finished. Modified to match ANSI
6 ;;; Common Lisp.
8 ;;;; Originally from:
9 ;;;; regression.lsp XLISP-STAT regression model proto and methods
10 ;;;; XLISP-STAT 2.1 Copyright (c) 1990, by Luke Tierney
11 ;;;; Additions to Xlisp 2.1, Copyright (c) 1989 by David Michael Betz
12 ;;;; You may give out copies of this software; for conditions see the file
13 ;;;; COPYING included with this distribution.
14 ;;;;
15 ;;;; Incorporates modifications suggested by Sandy Weisberg.
17 ;;; This version uses lisp-matrix for underlying numerics.
19 (in-package :lisp-stat-regression-linear)
21 ;;; Regresion Model Prototype
23 ;; The general strategy behind the fitting of models using prototypes
24 ;; is that we need to think about want the actual fits are, and then
25 ;; the fits can be used to recompute as components are changes. One
26 ;; catch here is that we'd like some notion of trace-ability, in
27 ;; particular, there is not necessarily a fixed way to take care of the
28 ;; audit trail. save-and-die might be a means of recording the final
29 ;; approach, but we are challenged by the problem of using advice and
30 ;; other such features to capture stages and steps that are considered
31 ;; along the goals of estimating a model.
33 ;; Note that the above is a stream-of-conscience response to the
34 ;; challenge of reproducibility in the setting of prototype "on-line"
35 ;; computation.
37 (defvar regression-model-proto nil
38 "Prototype for all regression model instances.")
40 (defproto regression-model-proto
41 '(x y intercept sweep-matrix basis weights
42 included
43 total-sum-of-squares
44 residual-sum-of-squares
45 predictor-names
46 response-name
47 case-labels
48 doc)
50 *object*
51 "Normal Linear Regression Model")
54 (defun regression-model
55 (x y &key
56 (intercept T)
57 (print T)
58 (weights nil)
59 (included (repeat t (vector-dimension y)))
60 predictor-names
61 response-name
62 case-labels
63 (doc "Undocumented Regression Model Instance")
64 (debug T))
65 "Args: (x y &key (intercept T) (print T) (weights nil)
66 included predictor-names response-name case-labels)
67 X - list of independent variables or X matrix
68 Y - dependent variable.
69 INTERCEPT - T to include (default), NIL for no intercept
70 PRINT - if not NIL print summary information
71 WEIGHTS - if supplied should be the same length as Y; error
72 variances are
73 assumed to be inversely proportional to WEIGHTS
74 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
75 - sequences of strings or symbols.
76 INCLUDED - if supplied should be the same length as Y, with
77 elements nil to skip a in computing estimates (but not
78 in residual analysis).
79 Returns a regression model object. To examine the model further assign the
80 result to a variable and send it messages.
81 Example (data are in file absorbtion.lsp in the sample data directory):
82 (def m (regression-model (list iron aluminum) absorbtion))
83 (send m :help) (send m :plot-residuals)"
84 (let ((x (cond
85 ((typep x 'matrix-like) x)
86 #| assume only numerical vectors -- but we need to ensure coercion to float.
87 ((or (typep x 'sequence)
88 (and (consp x)
89 (numberp (car x)))
90 (make-vector (length x) :initial-contents x)))
92 (t (error "not matrix-like.");x
93 ))) ;; actually, might should barf.
94 (y (cond
95 ((typep y 'vector-like) y)
97 ((and (consp x)
98 (numberp (car x))) (make-vector (length y) :initial-contents y))
100 (t (error "not vector-like."); y
101 ))) ;; actually, might should barf.
102 (m (send regression-model-proto :new)))
103 (format t "~%")
104 (send m :doc doc)
105 (send m :x x)
106 (send m :y y)
107 (send m :intercept intercept)
108 (send m :weights weights)
109 (send m :included included)
110 (send m :predictor-names predictor-names)
111 (send m :response-name response-name)
112 (send m :case-labels case-labels)
113 (if debug
114 (progn
115 (format t "~%")
116 (format t "~S~%" (send m :doc))
117 (format t "X: ~S~%" (send m :x))
118 (format t "Y: ~S~%" (send m :y))))
119 (if print (send m :display))
125 (defmeth regression-model-proto :isnew ()
126 (send self :needs-computing t))
128 (defmeth regression-model-proto :save ()
129 "Message args: ()
130 Returns an expression that will reconstruct the regression model."
131 `(regression-model ',(send self :x)
132 ',(send self :y)
133 :intercept ',(send self :intercept)
134 :weights ',(send self :weights)
135 :included ',(send self :included)
136 :predictor-names ',(send self :predictor-names)
137 :response-name ',(send self :response-name)
138 :case-labels ',(send self :case-labels)))
140 ;;; Computing and Display Methods
142 ;; [X|Y]t [X|Y]
143 ;; = XtX XtY
144 ;; YtX YtY
145 ;; so with (= (dim X) (list n p))
146 ;; we end up with p x p p x 1
147 ;; 1 x p 1 x 1
149 ;; and this can be implemented by
151 (setf XY (bind2 X Y :by :row))
152 (setf XYtXY (m* (transpose XY) XY))
154 ;; which is too procedural. Sigh, I meant
156 (setf XYtXY (let ((XY (bind2 X Y :by :row)))
157 (m* (transpose XY) XY)))
159 ;; which at least looks lispy.
161 (defmeth regression-model-proto :compute ()
162 "Message args: ()
163 Recomputes the estimates. For internal use by other messages"
164 (let* ((included (if-else (send self :included) 1d0 0d0))
165 (x (send self :x))
166 (y (send self :y))
167 (intercept (send self :intercept)) ;; T/nil
168 (weights (send self :weights)) ;; vector-like or nil
169 (w (if weights (* included weights) included))
170 (beta (send :beta-coefficents (lm x y)))
171 (xtxinv (send :xtxinv (XtXinv x)))
172 (m (make-sweep-matrix x y w)) ;;; ERROR HERE of course!
173 (n (matrix-dimension x 1))
174 (p (if intercept
175 (1- (matrix-dimension m 0))
176 (matrix-dimension m 0))) ;; remove intercept from # params -- right?
177 (tss ) ; recompute, since we aren't sweeping...
178 (tol (* 0.001
179 (reduce #'* (mapcar #'standard-deviation
180 (list-of-columns x))))))
181 (format t
182 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
183 sweep-result x y m tss)
184 (setf (slot-value 'sweep-matrix) (first sweep-result))
185 (setf (slot-value 'total-sum-of-squares) tss)
186 (setf (slot-value 'residual-sum-of-squares)
187 (mref (first sweep-result) p p))
188 ;; SOMETHING WRONG HERE! FIX-ME
189 (setf (slot-value 'basis)
190 (let ((b (remove 0 (second sweep-result))))
191 (if b (- (reduce #'- (reverse b)) 1)
192 (error "no columns could be swept"))))))
194 (defmeth regression-model-proto :needs-computing (&optional set)
195 "Message args: ( &optional set )
197 If value given, sets the flag for whether (re)computation is needed to
198 update the model fits."
199 (send self :nop)
200 (if set (setf (slot-value 'sweep-matrix) nil))
201 (null (slot-value 'sweep-matrix)))
203 (defmeth regression-model-proto :display ()
204 "Message args: ()
206 Prints the least squares regression summary. Variables not used in the fit
207 are marked as aliased."
208 (let ((coefs (coerce (send self :coef-estimates) 'list))
209 (se-s (send self :coef-standard-errors))
210 (x (send self :x))
211 (p-names (send self :predictor-names)))
212 (if (send self :weights)
213 (format t "~%Weighted Least Squares Estimates:~2%")
214 (format t "~%Least Squares Estimates:~2%"))
215 (when (send self :intercept)
216 (format t "Constant ~10f ~A~%"
217 (car coefs) (list (car se-s)))
218 (setf coefs (cdr coefs))
219 (setf se-s (cdr se-s)))
220 (dotimes (i (array-dimension x 1))
221 (cond
222 ((member i (send self :basis))
223 (format t "~22a ~10f ~A~%"
224 (select p-names i) (car coefs) (list (car se-s)))
225 (setf coefs (cdr coefs) se-s (cdr se-s)))
226 (t (format t "~22a aliased~%" (select p-names i)))))
227 (format t "~%")
228 (format t "R Squared: ~10f~%" (send self :r-squared))
229 (format t "Sigma hat: ~10f~%" (send self :sigma-hat))
230 (format t "Number of cases: ~10d~%" (send self :num-cases))
231 (if (/= (send self :num-cases) (send self :num-included))
232 (format t "Number of cases used: ~10d~%" (send self :num-included)))
233 (format t "Degrees of freedom: ~10d~%" (send self :df))
234 (format t "~%")))
236 ;;; Slot accessors and mutators
238 (defmeth regression-model-proto :doc (&optional new-doc append)
239 "Message args: (&optional new-doc)
241 Returns the DOC-STRING as supplied to m.
242 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
243 NEW-DOC. In this setting, when APPEND is T, don't replace and just
244 append NEW-DOC to DOC."
245 (send self :nop)
246 (when (and new-doc (stringp new-doc))
247 (setf (slot-value 'doc)
248 (if append
249 (concatenate 'string
250 (slot-value 'doc)
251 new-doc)
252 new-doc)))
253 (slot-value 'doc))
256 (defmeth regression-model-proto :x (&optional new-x)
257 "Message args: (&optional new-x)
259 With no argument returns the x matrix-like as supplied to m. With an
260 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
261 estimates."
262 (when (and new-x (typep new-x 'matrix-like))
263 (setf (slot-value 'x) new-x)
264 (send self :needs-computing t))
265 (slot-value 'x))
267 (defmeth regression-model-proto :y (&optional new-y)
268 "Message args: (&optional new-y)
270 With no argument returns the y vector-like as supplied to m. With an
271 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
272 estimates."
273 (when (and new-y
274 (typep new-y 'vector-like))
275 (setf (slot-value 'y) new-y) ;; fixme -- pls set slot value to a vector-like!
276 (send self :needs-computing t))
277 (slot-value 'y))
279 (defmeth regression-model-proto :intercept (&optional (val nil set))
280 "Message args: (&optional new-intercept)
282 With no argument returns T if the model includes an intercept term,
283 nil if not. With an argument NEW-INTERCEPT the model is changed to
284 include or exclude an intercept, according to the value of
285 NEW-INTERCEPT."
286 (when set
287 (setf (slot-value 'intercept) val)
288 (send self :needs-computing t))
289 (slot-value 'intercept))
291 (defmeth regression-model-proto :weights (&optional (new-w nil set))
292 "Message args: (&optional new-w)
294 With no argument returns the weight vector-like as supplied to m; NIL
295 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
296 and recomputes the estimates."
297 (when set
298 #| ;; probably need to use "check-type" or similar?
299 (and set nil
300 (or (= new-w nil)
301 (typep new-w 'vector-like)))
303 (setf (slot-value 'weights) new-w)
304 (send self :needs-computing t))
305 (slot-value 'weights))
307 (defmeth regression-model-proto :total-sum-of-squares ()
308 "Message args: ()
310 Returns the total sum of squares around the mean.
311 This is recomputed if an update is needed."
312 (if (send self :needs-computing)
313 (send self :compute))
314 (slot-value 'total-sum-of-squares))
316 (defmeth regression-model-proto :residual-sum-of-squares ()
317 "Message args: ()
319 Returns the residual sum of squares for the model.
320 This is recomputed if an update is needed."
321 (if (send self :needs-computing)
322 (send self :compute))
323 (slot-value 'residual-sum-of-squares))
325 (defmeth regression-model-proto :basis ()
326 "Message args: ()
328 Returns the indices of the variables used in fitting the model, in a
329 sequence.
330 This is recomputed if an update is needed."
331 (if (send self :needs-computing)
332 (send self :compute))
333 (slot-value 'basis))
335 (defmeth regression-model-proto :included (&optional new-included)
336 "Message args: (&optional new-included)
338 With no argument, NIL means a case is not used in calculating
339 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
340 of length of y of nil and t to select cases. Estimates are
341 recomputed."
342 (when new-included
344 (and new-included
345 (= (length new-included) (send self :num-cases)))
347 (setf (slot-value 'included) (copy-seq new-included))
348 (send self :needs-computing t))
349 (if (slot-value 'included)
350 (slot-value 'included)
351 (repeat t (send self :num-cases))))
353 (defmeth regression-model-proto :predictor-names (&optional (names nil set))
354 "Message args: (&optional (names nil set))
356 With no argument returns the predictor names. NAMES sets the names."
357 (if set (setf (slot-value 'predictor-names) (mapcar #'string names)))
358 (let ((p (matrix-dimension (send self :x) 1))
359 (p-names (slot-value 'predictor-names)))
360 (if (not (and p-names (= (length p-names) p)))
361 (setf (slot-value 'predictor-names)
362 (mapcar #'(lambda (a) (format nil "Variable ~a" a))
363 (iseq 0 (- p 1))))))
364 (slot-value 'predictor-names))
366 (defmeth regression-model-proto :response-name (&optional (name "Y" set))
367 "Message args: (&optional name)
369 With no argument returns the response name. NAME sets the name."
370 (send self :nop)
371 (if set (setf (slot-value 'response-name) (if name (string name) "Y")))
372 (slot-value 'response-name))
374 (defmeth regression-model-proto :case-labels (&optional (labels nil set))
375 "Message args: (&optional labels)
376 With no argument returns the case-labels. LABELS sets the labels."
377 (if set (setf (slot-value 'case-labels)
378 (if labels
379 (mapcar #'string labels)
380 (mapcar #'(lambda (x) (format nil "~d" x))
381 (iseq 0 (- (send self :num-cases) 1))))))
382 (slot-value 'case-labels))
385 ;;; Other Methods
386 ;;; None of these methods access any slots directly.
389 (defmeth regression-model-proto :num-cases ()
390 "Message args: ()
391 Returns the number of cases in the model."
392 (nelts (send self :y)))
394 (defmeth regression-model-proto :num-included ()
395 "Message args: ()
396 Returns the number of cases used in the computations."
397 (sum (if-else (send self :included) 1 0)))
399 (defmeth regression-model-proto :num-coefs ()
400 "Message args: ()
401 Returns the number of coefficients in the fit model (including the
402 intercept if the model includes one)."
403 (if (send self :intercept)
404 (+ 1 (nelts (send self :basis)))
405 (nelts (send self :basis))))
407 (defmeth regression-model-proto :df ()
408 "Message args: ()
409 Returns the number of degrees of freedom in the model."
410 (- (send self :num-included) (send self :num-coefs)))
412 (defmeth regression-model-proto :x-matrix ()
413 "Message args: ()
414 Returns the X matrix for the model, including a column of 1's, if
415 appropriate. Columns of X matrix correspond to entries in basis."
416 (let ((m (select (send self :x)
417 (iseq 0 (- (send self :num-cases) 1))
418 (send self :basis))))
419 (if (send self :intercept)
420 (bind2 (repeat 1 (send self :num-cases)) m)
421 m)))
423 (defmeth regression-model-proto :leverages ()
424 "Message args: ()
425 Returns the diagonal elements of the hat matrix."
426 (let* ((weights (send self :weights))
427 (x (send self :x-matrix))
428 (raw-levs
429 (m* (* (m* x (send self :xtxinv)) x)
430 (repeat 1 (send self :num-coefs)))))
431 (if weights (* weights raw-levs) raw-levs)))
433 (defmeth regression-model-proto :fit-values ()
434 "Message args: ()
435 Returns the fitted values for the model."
436 (m* (send self :x-matrix) (send self :coef-estimates)))
438 (defmeth regression-model-proto :raw-residuals ()
439 "Message args: ()
440 Returns the raw residuals for a model."
441 (- (send self :y) (send self :fit-values)))
443 (defmeth regression-model-proto :residuals ()
444 "Message args: ()
445 Returns the raw residuals for a model without weights. If the model
446 includes weights the raw residuals times the square roots of the weights
447 are returned."
448 (let ((raw-residuals (send self :raw-residuals))
449 (weights (send self :weights)))
450 (if weights (* (sqrt weights) raw-residuals) raw-residuals)))
452 (defmeth regression-model-proto :sum-of-squares ()
453 "Message args: ()
454 Returns the error sum of squares for the model."
455 (send self :residual-sum-of-squares))
457 (defmeth regression-model-proto :sigma-hat ()
458 "Message args: ()
459 Returns the estimated standard deviation of the deviations about the
460 regression line."
461 (let ((ss (send self :sum-of-squares))
462 (df (send self :df)))
463 (if (/= df 0) (sqrt (/ ss df)))))
465 ;; for models without an intercept the 'usual' formula for R^2 can give
466 ;; negative results; hence the max.
467 (defmeth regression-model-proto :r-squared ()
468 "Message args: ()
469 Returns the sample squared multiple correlation coefficient, R squared, for
470 the regression."
471 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
474 (defmeth regression-model-proto :coef-estimates ()
475 "Message args: ()
477 Returns the OLS (ordinary least squares) estimates of the regression
478 coefficients. Entries beyond the intercept correspond to entries in
479 basis."
480 (let ((n (matrix-dimension (send self :x) 1))
481 (indices (flatten-list
482 (if (send self :intercept)
483 (cons 0 (+ 1 (send self :basis)))
484 (list (+ 1 (send self :basis))))))
485 (m (send self :sweep-matrix)))
486 (format t "~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
487 m n indices (send self :basis))
488 (coerce (compound-data-seq (select m (1+ n) indices)) 'list))) ;; ERROR
490 (defmeth regression-model-proto :xtxinv ()
491 "Message args: ()
492 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
493 (let ((indices (if (send self :intercept)
494 (cons 0 (1+ (send self :basis)))
495 (1+ (send self :basis)))))
496 (select (send self :sweep-matrix) indices indices)))
498 (defmeth regression-model-proto :coef-standard-errors ()
499 "Message args: ()
500 Returns estimated standard errors of coefficients. Entries beyond the
501 intercept correspond to entries in basis."
502 (let ((s (send self :sigma-hat)))
503 (if s (* (send self :sigma-hat) (sqrt (diagonalf (send self :xtxinv)))))))
505 (defmeth regression-model-proto :studentized-residuals ()
506 "Message args: ()
507 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
508 (let ((res (send self :residuals))
509 (lev (send self :leverages))
510 (sig (send self :sigma-hat))
511 (inc (send self :included)))
512 (if-else inc
513 (/ res (* sig (sqrt (pmax .00001 (- 1 lev)))))
514 (/ res (* sig (sqrt (+ 1 lev)))))))
516 (defmeth regression-model-proto :externally-studentized-residuals ()
517 "Message args: ()
518 Computes the externally studentized residuals."
519 (let* ((res (send self :studentized-residuals))
520 (df (send self :df)))
521 (if-else (send self :included)
522 (* res (sqrt (/ (- df 1) (- df (^ res 2)))))
523 res)))
525 (defmeth regression-model-proto :cooks-distances ()
526 "Message args: ()
527 Computes Cook's distances."
528 (let ((lev (send self :leverages))
529 (res (/ (^ (send self :studentized-residuals) 2)
530 (send self :num-coefs))))
531 (if-else (send self :included) (* res (/ lev (- 1 lev) )) (* res lev))))
534 (defun plot-points (x y &rest args)
535 "need to fix."
536 (declare (ignore x y args))
537 (error "Graphics not implemented yet."))
539 ;; Can not plot points yet!!
540 (defmeth regression-model-proto :plot-residuals (&optional x-values)
541 "Message args: (&optional x-values)
542 Opens a window with a plot of the residuals. If X-VALUES are not supplied
543 the fitted values are used. The plot can be linked to other plots with the
544 link-views function. Returns a plot object."
545 (plot-points (if x-values x-values (send self :fit-values))
546 (send self :residuals)
547 :title "Residual Plot"
548 :point-labels (send self :case-labels)))
550 (defmeth regression-model-proto :plot-bayes-residuals
551 (&optional x-values)
552 "Message args: (&optional x-values)
554 Opens a window with a plot of the standardized residuals and two
555 standard error bars for the posterior distribution of the actual
556 deviations from the line. See Chaloner and Brant. If X-VALUES are not
557 supplied the fitted values are used. The plot can be linked to other
558 plots with the link-views function. Returns a plot object."
560 (let* ((r (/ (send self :residuals)
561 (send self :sigma-hat)))
562 (d (* 2 (sqrt (send self :leverages))))
563 (low (- r d))
564 (high (+ r d))
565 (x-values (if x-values x-values (send self :fit-values)))
566 (p (plot-points x-values r
567 :title "Bayes Residual Plot"
568 :point-labels (send self :case-labels))))
569 (map 'list #'(lambda (a b c d) (send p :plotline a b c d nil))
570 x-values low x-values high)
571 (send p :adjust-to-data)