Move LM command initially into regression.lisp, continue to work
[CommonLispStat.git] / src / stat-models / regression.lisp
blob12dbceed0f856c1111dd3af8ba6ef22756e52a60
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")
55 ;; might add args: (method 'gelsy), or do we want to put a more
56 ;; general front end, linear-least-square, across the range of
57 ;; LAPACK solvers?
58 (defun lm (x y &optional rcond (intercept T))
59 "fit the linear model:
60 y = x \beta + e
62 and estimate \beta. X,Y should be in cases-by-vars form, i.e. X
63 should be n x p, Y should be n x 1. Returns estimates, n and p.
64 Probably should return a form providing the call, as well.
66 R's lm object returns: coefficients, residuals, effects, rank, fitted,
67 qr-results for numerical considerations, DF_resid. Need to
68 encapsulate into a class or struct."
69 (check-type x matrix-like)
70 (check-type y vector-like) ; vector-like might be too strict?
71 ; maybe matrix-like?
72 (assert (= (nrows y) (nrows x)) ; same number of observations/cases
73 (x y) "Can not multiply x:~S by y:~S" x y)
74 (let ((x1 (if intercept
75 (bind2 (ones (matrix-dimension x 0) 1)
76 x :by :column)
77 x)))
78 (let ((betahat (gelsy (m* (transpose x1) x1)
79 (m* (transpose x1) y)
80 (if rcond rcond (*
81 (coerce (expt 2 -52) 'double-float)
82 (max (nrows x1)
83 (ncols y))))))
84 (betahat1 (gelsy x1
86 (if rcond rcond
87 (* (coerce (expt 2 -52) 'double-float)
88 (max (nrows x1)
89 (ncols y)))))))
90 ;; need computation for SEs,
91 (format t "")
92 (list betahat ; LA-SIMPLE-VECTOR-DOUBLE
93 betahat1 ; LA-SLICE-VECVIEW-DOUBLE
94 (xtxinv x1); (sebetahat betahat x y) ; TODO: write me!
95 (nrows x) ; surrogate for n
96 (ncols x1) ; surrogate for p
97 (v- (first betahat) (first betahat1))))))
102 (defun regression-model
103 (x y &key
104 (intercept T)
105 (print T)
106 (weights nil)
107 (included (repeat t (vector-dimension y)))
108 predictor-names
109 response-name
110 case-labels
111 (doc "Undocumented Regression Model Instance")
112 (debug T))
113 "Args: (x y &key (intercept T) (print T) (weights nil)
114 included predictor-names response-name case-labels)
115 X - list of independent variables or X matrix
116 Y - dependent variable.
117 INTERCEPT - T to include (default), NIL for no intercept
118 PRINT - if not NIL print summary information
119 WEIGHTS - if supplied should be the same length as Y; error
120 variances are
121 assumed to be inversely proportional to WEIGHTS
122 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
123 - sequences of strings or symbols.
124 INCLUDED - if supplied should be the same length as Y, with
125 elements nil to skip a in computing estimates (but not
126 in residual analysis).
127 Returns a regression model object. To examine the model further assign the
128 result to a variable and send it messages.
129 Example (data are in file absorbtion.lsp in the sample data directory):
130 (def m (regression-model (list iron aluminum) absorbtion))
131 (send m :help) (send m :plot-residuals)"
132 (let ((x (cond
133 ((typep x 'matrix-like) x)
134 #| assume only numerical vectors -- but we need to ensure coercion to float.
135 ((or (typep x 'sequence)
136 (and (consp x)
137 (numberp (car x)))
138 (make-vector (length x) :initial-contents x)))
140 (t (error "not matrix-like.");x
141 ))) ;; actually, might should barf.
142 (y (cond
143 ((typep y 'vector-like) y)
145 ((and (consp x)
146 (numberp (car x))) (make-vector (length y) :initial-contents y))
148 (t (error "not vector-like."); y
149 ))) ;; actually, might should barf.
150 (m (send regression-model-proto :new)))
151 (format t "~%")
152 (send m :doc doc)
153 (send m :x x)
154 (send m :y y)
155 (send m :intercept intercept)
156 (send m :weights weights)
157 (send m :included included)
158 (send m :predictor-names predictor-names)
159 (send m :response-name response-name)
160 (send m :case-labels case-labels)
161 (if debug
162 (progn
163 (format t "~%")
164 (format t "~S~%" (send m :doc))
165 (format t "X: ~S~%" (send m :x))
166 (format t "Y: ~S~%" (send m :y))))
167 (if print (send m :display))
173 (defmeth regression-model-proto :isnew ()
174 (send self :needs-computing t))
176 (defmeth regression-model-proto :save ()
177 "Message args: ()
178 Returns an expression that will reconstruct the regression model."
179 `(regression-model ',(send self :x)
180 ',(send self :y)
181 :intercept ',(send self :intercept)
182 :weights ',(send self :weights)
183 :included ',(send self :included)
184 :predictor-names ',(send self :predictor-names)
185 :response-name ',(send self :response-name)
186 :case-labels ',(send self :case-labels)))
188 ;;; Computing and Display Methods
190 ;; [X|Y]t [X|Y]
191 ;; = XtX XtY
192 ;; YtX YtY
193 ;; so with (= (dim X) (list n p))
194 ;; we end up with p x p p x 1
195 ;; 1 x p 1 x 1
197 ;; and this can be implemented by
199 (setf XY (bind2 X Y :by :row))
200 (setf XYtXY (m* (transpose XY) XY))
202 ;; which is too procedural. Sigh, I meant
204 (setf XYtXY (let ((XY (bind2 X Y :by :row)))
205 (m* (transpose XY) XY)))
207 ;; which at least looks lispy.
209 (defmeth regression-model-proto :compute ()
210 "Message args: ()
211 Recomputes the estimates. For internal use by other messages"
212 (let* ((included (if-else (send self :included) 1d0 0d0))
213 (x (send self :x))
214 (y (send self :y))
215 (intercept (send self :intercept)) ;; T/nil
216 (weights (send self :weights)) ;; vector-like or nil
217 (w (if weights (* included weights) included))
218 (m (make-sweep-matrix x y w)) ;;; ERROR HERE of course!
219 (n (matrix-dimension x 1))
220 (p (if intercept
221 (1- (matrix-dimension m 0))
222 (matrix-dimension m 0))) ;; remove intercept from # params -- right?
223 (tss ) ; recompute, since we aren't sweeping...
224 (tol (* 0.001
225 (reduce #'* (mapcar #'standard-deviation
226 (list-of-columns x))))))
227 (format t
228 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
229 sweep-result x y m tss)
231 (send self :beta-coefficents (lm x y))
232 (send self :xtxinv (xtxinv x)) ;; could extract from (lm ...)
234 (setf (slot-value 'sweep-matrix) (first sweep-result))
235 (setf (slot-value 'total-sum-of-squares) tss)
236 (setf (slot-value 'residual-sum-of-squares)
237 (mref (first sweep-result) p p))
238 ;; SOMETHING WRONG HERE! FIX-ME
239 (setf (slot-value 'basis)
240 (let ((b (remove 0 (second sweep-result))))
241 (if b (- (reduce #'- (reverse b)) 1)
242 (error "no columns could be swept"))))))
244 (defmeth regression-model-proto :needs-computing (&optional set)
245 "Message args: ( &optional set )
247 If value given, sets the flag for whether (re)computation is needed to
248 update the model fits."
249 (send self :nop)
250 (if set (setf (slot-value 'sweep-matrix) nil))
251 (null (slot-value 'sweep-matrix)))
253 (defmeth regression-model-proto :display ()
254 "Message args: ()
256 Prints the least squares regression summary. Variables not used in the fit
257 are marked as aliased."
258 (let ((coefs (coerce (send self :coef-estimates) 'list))
259 (se-s (send self :coef-standard-errors))
260 (x (send self :x))
261 (p-names (send self :predictor-names)))
262 (if (send self :weights)
263 (format t "~%Weighted Least Squares Estimates:~2%")
264 (format t "~%Least Squares Estimates:~2%"))
265 (when (send self :intercept)
266 (format t "Constant ~10f ~A~%"
267 (car coefs) (list (car se-s)))
268 (setf coefs (cdr coefs))
269 (setf se-s (cdr se-s)))
270 (dotimes (i (array-dimension x 1))
271 (cond
272 ((member i (send self :basis))
273 (format t "~22a ~10f ~A~%"
274 (select p-names i) (car coefs) (list (car se-s)))
275 (setf coefs (cdr coefs) se-s (cdr se-s)))
276 (t (format t "~22a aliased~%" (select p-names i)))))
277 (format t "~%")
278 (format t "R Squared: ~10f~%" (send self :r-squared))
279 (format t "Sigma hat: ~10f~%" (send self :sigma-hat))
280 (format t "Number of cases: ~10d~%" (send self :num-cases))
281 (if (/= (send self :num-cases) (send self :num-included))
282 (format t "Number of cases used: ~10d~%" (send self :num-included)))
283 (format t "Degrees of freedom: ~10d~%" (send self :df))
284 (format t "~%")))
286 ;;; Slot accessors and mutators
288 (defmeth regression-model-proto :doc (&optional new-doc append)
289 "Message args: (&optional new-doc)
291 Returns the DOC-STRING as supplied to m.
292 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
293 NEW-DOC. In this setting, when APPEND is T, don't replace and just
294 append NEW-DOC to DOC."
295 (send self :nop)
296 (when (and new-doc (stringp new-doc))
297 (setf (slot-value 'doc)
298 (if append
299 (concatenate 'string
300 (slot-value 'doc)
301 new-doc)
302 new-doc)))
303 (slot-value 'doc))
306 (defmeth regression-model-proto :x (&optional new-x)
307 "Message args: (&optional new-x)
309 With no argument returns the x matrix-like as supplied to m. With an
310 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
311 estimates."
312 (when (and new-x (typep new-x 'matrix-like))
313 (setf (slot-value 'x) new-x)
314 (send self :needs-computing t))
315 (slot-value 'x))
317 (defmeth regression-model-proto :y (&optional new-y)
318 "Message args: (&optional new-y)
320 With no argument returns the y vector-like as supplied to m. With an
321 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
322 estimates."
323 (when (and new-y
324 (typep new-y 'vector-like))
325 (setf (slot-value 'y) new-y) ;; fixme -- pls set slot value to a vector-like!
326 (send self :needs-computing t))
327 (slot-value 'y))
329 (defmeth regression-model-proto :intercept (&optional (val nil set))
330 "Message args: (&optional new-intercept)
332 With no argument returns T if the model includes an intercept term,
333 nil if not. With an argument NEW-INTERCEPT the model is changed to
334 include or exclude an intercept, according to the value of
335 NEW-INTERCEPT."
336 (when set
337 (setf (slot-value 'intercept) val)
338 (send self :needs-computing t))
339 (slot-value 'intercept))
341 (defmeth regression-model-proto :weights (&optional (new-w nil set))
342 "Message args: (&optional new-w)
344 With no argument returns the weight vector-like as supplied to m; NIL
345 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
346 and recomputes the estimates."
347 (when set
348 #| ;; probably need to use "check-type" or similar?
349 (and set nil
350 (or (= new-w nil)
351 (typep new-w 'vector-like)))
353 (setf (slot-value 'weights) new-w)
354 (send self :needs-computing t))
355 (slot-value 'weights))
357 (defmeth regression-model-proto :total-sum-of-squares ()
358 "Message args: ()
360 Returns the total sum of squares around the mean.
361 This is recomputed if an update is needed."
362 (if (send self :needs-computing)
363 (send self :compute))
364 (slot-value 'total-sum-of-squares))
366 (defmeth regression-model-proto :residual-sum-of-squares ()
367 "Message args: ()
369 Returns the residual sum of squares for the model.
370 This is recomputed if an update is needed."
371 (if (send self :needs-computing)
372 (send self :compute))
373 (slot-value 'residual-sum-of-squares))
375 (defmeth regression-model-proto :basis ()
376 "Message args: ()
378 Returns the indices of the variables used in fitting the model, in a
379 sequence.
380 This is recomputed if an update is needed."
381 (if (send self :needs-computing)
382 (send self :compute))
383 (slot-value 'basis))
385 (defmeth regression-model-proto :included (&optional new-included)
386 "Message args: (&optional new-included)
388 With no argument, NIL means a case is not used in calculating
389 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
390 of length of y of nil and t to select cases. Estimates are
391 recomputed."
392 (when new-included
394 (and new-included
395 (= (length new-included) (send self :num-cases)))
397 (setf (slot-value 'included) (copy-seq new-included))
398 (send self :needs-computing t))
399 (if (slot-value 'included)
400 (slot-value 'included)
401 (repeat t (send self :num-cases))))
403 (defmeth regression-model-proto :predictor-names (&optional (names nil set))
404 "Message args: (&optional (names nil set))
406 With no argument returns the predictor names. NAMES sets the names."
407 (if set (setf (slot-value 'predictor-names) (mapcar #'string names)))
408 (let ((p (matrix-dimension (send self :x) 1))
409 (p-names (slot-value 'predictor-names)))
410 (if (not (and p-names (= (length p-names) p)))
411 (setf (slot-value 'predictor-names)
412 (mapcar #'(lambda (a) (format nil "Variable ~a" a))
413 (iseq 0 (- p 1))))))
414 (slot-value 'predictor-names))
416 (defmeth regression-model-proto :response-name (&optional (name "Y" set))
417 "Message args: (&optional name)
419 With no argument returns the response name. NAME sets the name."
420 (send self :nop)
421 (if set (setf (slot-value 'response-name) (if name (string name) "Y")))
422 (slot-value 'response-name))
424 (defmeth regression-model-proto :case-labels (&optional (labels nil set))
425 "Message args: (&optional labels)
426 With no argument returns the case-labels. LABELS sets the labels."
427 (if set (setf (slot-value 'case-labels)
428 (if labels
429 (mapcar #'string labels)
430 (mapcar #'(lambda (x) (format nil "~d" x))
431 (iseq 0 (- (send self :num-cases) 1))))))
432 (slot-value 'case-labels))
435 ;;; Other Methods
436 ;;; None of these methods access any slots directly.
439 (defmeth regression-model-proto :num-cases ()
440 "Message args: ()
441 Returns the number of cases in the model."
442 (nelts (send self :y)))
444 (defmeth regression-model-proto :num-included ()
445 "Message args: ()
446 Returns the number of cases used in the computations."
447 (sum (if-else (send self :included) 1 0)))
449 (defmeth regression-model-proto :num-coefs ()
450 "Message args: ()
451 Returns the number of coefficients in the fit model (including the
452 intercept if the model includes one)."
453 (if (send self :intercept)
454 (+ 1 (nelts (send self :basis)))
455 (nelts (send self :basis))))
457 (defmeth regression-model-proto :df ()
458 "Message args: ()
459 Returns the number of degrees of freedom in the model."
460 (- (send self :num-included) (send self :num-coefs)))
462 (defmeth regression-model-proto :x-matrix ()
463 "Message args: ()
464 Returns the X matrix for the model, including a column of 1's, if
465 appropriate. Columns of X matrix correspond to entries in basis."
466 (let ((m (select (send self :x)
467 (iseq 0 (- (send self :num-cases) 1))
468 (send self :basis))))
469 (if (send self :intercept)
470 (bind2 (repeat 1 (send self :num-cases)) m)
471 m)))
473 (defmeth regression-model-proto :leverages ()
474 "Message args: ()
475 Returns the diagonal elements of the hat matrix."
476 (let* ((weights (send self :weights))
477 (x (send self :x-matrix))
478 (raw-levs
479 (m* (* (m* x (send self :xtxinv)) x)
480 (repeat 1 (send self :num-coefs)))))
481 (if weights (* weights raw-levs) raw-levs)))
483 (defmeth regression-model-proto :fit-values ()
484 "Message args: ()
485 Returns the fitted values for the model."
486 (m* (send self :x-matrix) (send self :coef-estimates)))
488 (defmeth regression-model-proto :raw-residuals ()
489 "Message args: ()
490 Returns the raw residuals for a model."
491 (- (send self :y) (send self :fit-values)))
493 (defmeth regression-model-proto :residuals ()
494 "Message args: ()
495 Returns the raw residuals for a model without weights. If the model
496 includes weights the raw residuals times the square roots of the weights
497 are returned."
498 (let ((raw-residuals (send self :raw-residuals))
499 (weights (send self :weights)))
500 (if weights (* (sqrt weights) raw-residuals) raw-residuals)))
502 (defmeth regression-model-proto :sum-of-squares ()
503 "Message args: ()
504 Returns the error sum of squares for the model."
505 (send self :residual-sum-of-squares))
507 (defmeth regression-model-proto :sigma-hat ()
508 "Message args: ()
509 Returns the estimated standard deviation of the deviations about the
510 regression line."
511 (let ((ss (send self :sum-of-squares))
512 (df (send self :df)))
513 (if (/= df 0) (sqrt (/ ss df)))))
515 ;; for models without an intercept the 'usual' formula for R^2 can give
516 ;; negative results; hence the max.
517 (defmeth regression-model-proto :r-squared ()
518 "Message args: ()
519 Returns the sample squared multiple correlation coefficient, R squared, for
520 the regression."
521 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
524 (defmeth regression-model-proto :coef-estimates ()
525 "Message args: ()
527 Returns the OLS (ordinary least squares) estimates of the regression
528 coefficients. Entries beyond the intercept correspond to entries in
529 basis."
530 (let ((n (matrix-dimension (send self :x) 1))
531 (indices (flatten-list
532 (if (send self :intercept)
533 (cons 0 (+ 1 (send self :basis)))
534 (list (+ 1 (send self :basis))))))
535 (m (send self :sweep-matrix)))
536 (format t "~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
537 m n indices (send self :basis))
538 (coerce (compound-data-seq (select m (1+ n) indices)) 'list))) ;; ERROR
540 (defmeth regression-model-proto :xtxinv ()
541 "Message args: ()
542 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
543 (let ((indices (if (send self :intercept)
544 (cons 0 (1+ (send self :basis)))
545 (1+ (send self :basis)))))
546 (select (send self :sweep-matrix) indices indices)))
548 (defmeth regression-model-proto :coef-standard-errors ()
549 "Message args: ()
550 Returns estimated standard errors of coefficients. Entries beyond the
551 intercept correspond to entries in basis."
552 (let ((s (send self :sigma-hat)))
553 (if s (* (send self :sigma-hat) (sqrt (diagonalf (send self :xtxinv)))))))
555 (defmeth regression-model-proto :studentized-residuals ()
556 "Message args: ()
557 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
558 (let ((res (send self :residuals))
559 (lev (send self :leverages))
560 (sig (send self :sigma-hat))
561 (inc (send self :included)))
562 (if-else inc
563 (/ res (* sig (sqrt (max .00001 (- 1 lev))))) ; vectorize max
564 (/ res (* sig (sqrt (+ 1 lev)))))))
566 (defmeth regression-model-proto :externally-studentized-residuals ()
567 "Message args: ()
568 Computes the externally studentized residuals."
569 (let* ((res (send self :studentized-residuals))
570 (df (send self :df)))
571 (if-else (send self :included)
572 (* res (sqrt (/ (- df 1) (- df (^ res 2)))))
573 res)))
575 (defmeth regression-model-proto :cooks-distances ()
576 "Message args: ()
577 Computes Cook's distances."
578 (let ((lev (send self :leverages))
579 (res (/ (^ (send self :studentized-residuals) 2)
580 (send self :num-coefs))))
581 (if-else (send self :included) (* res (/ lev (- 1 lev) )) (* res lev))))
584 (defun plot-points (x y &rest args)
585 "need to fix."
586 (declare (ignore x y args))
587 (error "Graphics not implemented yet."))
589 ;; Can not plot points yet!!
590 (defmeth regression-model-proto :plot-residuals (&optional x-values)
591 "Message args: (&optional x-values)
592 Opens a window with a plot of the residuals. If X-VALUES are not supplied
593 the fitted values are used. The plot can be linked to other plots with the
594 link-views function. Returns a plot object."
595 (plot-points (if x-values x-values (send self :fit-values))
596 (send self :residuals)
597 :title "Residual Plot"
598 :point-labels (send self :case-labels)))
600 (defmeth regression-model-proto :plot-bayes-residuals
601 (&optional x-values)
602 "Message args: (&optional x-values)
604 Opens a window with a plot of the standardized residuals and two
605 standard error bars for the posterior distribution of the actual
606 deviations from the line. See Chaloner and Brant. If X-VALUES are not
607 supplied the fitted values are used. The plot can be linked to other
608 plots with the link-views function. Returns a plot object."
610 (let* ((r (/ (send self :residuals)
611 (send self :sigma-hat)))
612 (d (* 2 (sqrt (send self :leverages))))
613 (low (- r d))
614 (high (+ r d))
615 (x-values (if x-values x-values (send self :fit-values)))
616 (p (plot-points x-values r
617 :title "Bayes Residual Plot"
618 :point-labels (send self :case-labels))))
619 (map 'list #'(lambda (a b c d) (send p :plotline a b c d nil))
620 x-values low x-values high)
621 (send p :adjust-to-data)