map to lisp-matrix supplemental ops (column-list -> list-of-columns).
[CommonLispStat.git] / src / stat-models / regression.lisp
blob1cc416696639f77932e699d6e49f098ac7daaa37
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-old
55 (x y &key
56 (intercept T)
57 (print T)
58 (weights nil)
59 (included (repeat t (length 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 ((or (typep x 'vector)
87 (and (consp x)
88 (numberp (car x))) (make-vector (length x) :initial-contents x)))
89 (t x))) ;; actually, might should barf.
90 (y (cond
91 ((typep y 'vector-like) y)
92 ((and (consp x)
93 (numberp (car x))) (make-vector (length y) :initial-contents y))
94 (t y))) ;; actually, might should barf.
95 (m (send regression-model-proto :new)))
96 (format t "~%")
97 (send m :doc doc)
98 (send m :x x)
99 (send m :y y)
100 (send m :intercept intercept)
101 (send m :weights weights)
102 (send m :included included)
103 (send m :predictor-names predictor-names)
104 (send m :response-name response-name)
105 (send m :case-labels case-labels)
106 (if debug
107 (progn
108 (format t "~%")
109 (format t "~S~%" (send m :doc))
110 (format t "X: ~S~%" (send m :x))
111 (format t "Y: ~S~%" (send m :y))))
112 (if print (send m :display))
117 (defun regression-model ;; assumes x/y from lisp-matrix -- start of a set of generics.
118 (x y &key
119 (intercept T)
120 (print T)
121 (weights nil)
122 (included (repeat t (length y)))
123 predictor-names
124 response-name
125 case-labels
126 (doc "Undocumented Regression Model Instance")
127 (debug T))
128 "Args: (x y &key (intercept T) (print T) (weights nil)
129 included predictor-names response-name case-labels)
130 X - list of independent variables or X matrix
131 Y - dependent variable.
132 INTERCEPT - T to include (default), NIL for no intercept
133 PRINT - if not NIL print summary information
134 WEIGHTS - if supplied should be the same length as Y; error
135 variances are
136 assumed to be inversely proportional to WEIGHTS
137 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
138 - sequences of strings or symbols.
139 INCLUDED - if supplied should be the same length as Y, with
140 elements nil to skip a in computing estimates (but not
141 in residual analysis).
142 Returns a regression model object. To examine the model further assign the
143 result to a variable and send it messages.
144 Example (data are in file absorbtion.lsp in the sample data directory):
145 (def m (regression-model (list iron aluminum) absorbtion))
146 (send m :help) (send m :plot-residuals)"
147 (let ((m (send regression-model-proto :new)))
148 (format t "~%")
149 (send m :doc doc)
150 (send m :x x)
151 (send m :y y)
152 (send m :intercept intercept)
153 (send m :weights weights)
154 (send m :included included)
155 (send m :predictor-names predictor-names)
156 (send m :response-name response-name)
157 (send m :case-labels case-labels)
158 (if debug
159 (progn
160 (format t "~%")
161 (format t "~S~%" (send m :doc))
162 (format t "X: ~S~%" (send m :x))
163 (format t "Y: ~S~%" (send m :y))))
164 (if print (send m :display))
168 (defmeth regression-model-proto :isnew ()
169 (send self :needs-computing t))
171 (defmeth regression-model-proto :save ()
172 "Message args: ()
173 Returns an expression that will reconstruct the regression model."
174 `(regression-model ',(send self :x)
175 ',(send self :y)
176 :intercept ',(send self :intercept)
177 :weights ',(send self :weights)
178 :included ',(send self :included)
179 :predictor-names ',(send self :predictor-names)
180 :response-name ',(send self :response-name)
181 :case-labels ',(send self :case-labels)))
183 ;;; Computing and Display Methods
185 (defmeth regression-model-proto :compute ()
186 "Message args: ()
187 Recomputes the estimates. For internal use by other messages"
188 (let* ((included (if-else (send self :included) 1 0))
189 (x (send self :x))
190 (y (send self :y))
191 (intercept (send self :intercept))
192 (weights (send self :weights))
193 (w (if weights (* included weights) included))
194 (m (make-sweep-matrix x y w)) ;;; ERROR HERE
195 (n (matrix-dimension x 1))
196 (p (- (matrix-dimension m 0) 1))
197 (tss (mref m p p))
198 (tol (* 0.001
199 (reduce #'* (mapcar #'standard-deviation (list-of-columns x)))))
200 (sweep-result
201 (if intercept
202 (sweep-operator m (iseq 1 n) tol)
203 (sweep-operator m (iseq 0 n) (cons 0.0 tol)))))
204 (format t
205 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
206 sweep-result x y m tss)
207 (setf (slot-value 'sweep-matrix) (first sweep-result))
208 (setf (slot-value 'total-sum-of-squares) tss)
209 (setf (slot-value 'residual-sum-of-squares)
210 (mref (first sweep-result) p p))
211 ;; SOMETHING WRONG HERE! FIX-ME
212 (setf (slot-value 'basis)
213 (let ((b (remove 0 (second sweep-result))))
214 (if b (- (reduce #'- (reverse b)) 1)
215 (error "no columns could be swept"))))))
217 (defmeth regression-model-proto :needs-computing (&optional set)
218 "Message args: ( &optional set )
220 If value given, sets the flag for whether (re)computation is needed to
221 update the model fits."
222 (send self :nop)
223 (if set (setf (slot-value 'sweep-matrix) nil))
224 (null (slot-value 'sweep-matrix)))
226 (defmeth regression-model-proto :display ()
227 "Message args: ()
229 Prints the least squares regression summary. Variables not used in the fit
230 are marked as aliased."
231 (let ((coefs (coerce (send self :coef-estimates) 'list))
232 (se-s (send self :coef-standard-errors))
233 (x (send self :x))
234 (p-names (send self :predictor-names)))
235 (if (send self :weights)
236 (format t "~%Weighted Least Squares Estimates:~2%")
237 (format t "~%Least Squares Estimates:~2%"))
238 (when (send self :intercept)
239 (format t "Constant ~10f ~A~%"
240 (car coefs) (list (car se-s)))
241 (setf coefs (cdr coefs))
242 (setf se-s (cdr se-s)))
243 (dotimes (i (array-dimension x 1))
244 (cond
245 ((member i (send self :basis))
246 (format t "~22a ~10f ~A~%"
247 (select p-names i) (car coefs) (list (car se-s)))
248 (setf coefs (cdr coefs) se-s (cdr se-s)))
249 (t (format t "~22a aliased~%" (select p-names i)))))
250 (format t "~%")
251 (format t "R Squared: ~10f~%" (send self :r-squared))
252 (format t "Sigma hat: ~10f~%" (send self :sigma-hat))
253 (format t "Number of cases: ~10d~%" (send self :num-cases))
254 (if (/= (send self :num-cases) (send self :num-included))
255 (format t "Number of cases used: ~10d~%" (send self :num-included)))
256 (format t "Degrees of freedom: ~10d~%" (send self :df))
257 (format t "~%")))
259 ;;; Slot accessors and mutators
261 (defmeth regression-model-proto :doc (&optional new-doc append)
262 "Message args: (&optional new-doc)
264 Returns the DOC-STRING as supplied to m.
265 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
266 NEW-DOC. In this setting, when APPEND is T, append NEW-DOC to DOC
267 rather than doing replacement."
268 (send self :nop)
269 (when (and new-doc (stringp new-doc))
270 (setf (slot-value 'doc)
271 (if append
272 (concatenate 'string
273 (slot-value 'doc)
274 new-doc)
275 new-doc)))
276 (slot-value 'doc))
279 (defmeth regression-model-proto :x (&optional new-x)
280 "Message args: (&optional new-x)
282 With no argument returns the x matrix-like as supplied to m. With an
283 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
284 estimates."
285 (when (and new-x (typep new-x 'matrix-like))
286 (setf (slot-value 'x) new-x)
287 (send self :needs-computing t))
288 (slot-value 'x))
290 (defmeth regression-model-proto :y (&optional new-y)
291 "Message args: (&optional new-y)
293 With no argument returns the y vector-like as supplied to m. With an
294 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
295 estimates."
296 (when (and new-y
297 (typep new-y 'vector-like))
298 (setf (slot-value 'y) new-y) ;; fixme -- pls set slot value to a vector-like!
299 (send self :needs-computing t))
300 (slot-value 'y))
302 (defmeth regression-model-proto :intercept (&optional (val nil set))
303 "Message args: (&optional new-intercept)
305 With no argument returns T if the model includes an intercept term,
306 nil if not. With an argument NEW-INTERCEPT the model is changed to
307 include or exclude an intercept, according to the value of
308 NEW-INTERCEPT."
309 (when set
310 (setf (slot-value 'intercept) val)
311 (send self :needs-computing t))
312 (slot-value 'intercept))
314 (defmeth regression-model-proto :weights (&optional (new-w nil set))
315 "Message args: (&optional new-w)
317 With no argument returns the weight vector-like as supplied to m; NIL
318 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
319 and recomputes the estimates."
320 (when (and set
321 (typep new-w 'vector-like))
322 (setf (slot-value 'weights) new-w)
323 (send self :needs-computing t))
324 (slot-value 'weights))
326 (defmeth regression-model-proto :total-sum-of-squares ()
327 "Message args: ()
329 Returns the total sum of squares around the mean.
330 This is recomputed if an update is needed."
331 (if (send self :needs-computing)
332 (send self :compute))
333 (slot-value 'total-sum-of-squares))
335 (defmeth regression-model-proto :residual-sum-of-squares ()
336 "Message args: ()
338 Returns the residual sum of squares for the model.
339 This is recomputed if an update is needed."
340 (if (send self :needs-computing)
341 (send self :compute))
342 (slot-value 'residual-sum-of-squares))
344 (defmeth regression-model-proto :basis ()
345 "Message args: ()
347 Returns the indices of the variables used in fitting the model, in a
348 sequence.
349 This is recomputed if an update is needed."
350 (if (send self :needs-computing)
351 (send self :compute))
352 (slot-value 'basis))
355 (defmeth regression-model-proto :sweep-matrix ()
356 "Message args: ()
358 Returns the swept sweep matrix. For internal use"
359 (if (send self :needs-computing)
360 (send self :compute))
361 (slot-value 'sweep-matrix))
363 (defmeth regression-model-proto :included (&optional new-included)
364 "Message args: (&optional new-included)
366 With no argument, NIL means a case is not used in calculating
367 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
368 of length of y of nil and t to select cases. Estimates are
369 recomputed."
370 (when (and new-included
371 (= (nelts new-included) (send self :num-cases)))
372 (setf (slot-value 'included) (copy-seq new-included))
373 (send self :needs-computing t))
374 (if (slot-value 'included)
375 (slot-value 'included)
376 (repeat t (send self :num-cases))))
378 (defmeth regression-model-proto :predictor-names (&optional (names nil set))
379 "Message args: (&optional (names nil set))
381 With no argument returns the predictor names. NAMES sets the names."
382 (if set (setf (slot-value 'predictor-names) (mapcar #'string names)))
383 (let ((p (matrix-dimension (send self :x) 1))
384 (p-names (slot-value 'predictor-names)))
385 (if (not (and p-names (= (length p-names) p)))
386 (setf (slot-value 'predictor-names)
387 (mapcar #'(lambda (a) (format nil "Variable ~a" a))
388 (iseq 0 (- p 1))))))
389 (slot-value 'predictor-names))
391 (defmeth regression-model-proto :response-name (&optional (name "Y" set))
392 "Message args: (&optional name)
394 With no argument returns the response name. NAME sets the name."
395 (send self :nop)
396 (if set (setf (slot-value 'response-name) (if name (string name) "Y")))
397 (slot-value 'response-name))
399 (defmeth regression-model-proto :case-labels (&optional (labels nil set))
400 "Message args: (&optional labels)
401 With no argument returns the case-labels. LABELS sets the labels."
402 (if set (setf (slot-value 'case-labels)
403 (if labels
404 (mapcar #'string labels)
405 (mapcar #'(lambda (x) (format nil "~d" x))
406 (iseq 0 (- (send self :num-cases) 1))))))
407 (slot-value 'case-labels))
410 ;;; Other Methods
411 ;;; None of these methods access any slots directly.
414 (defmeth regression-model-proto :num-cases ()
415 "Message args: ()
416 Returns the number of cases in the model."
417 (nelts (send self :y)))
419 (defmeth regression-model-proto :num-included ()
420 "Message args: ()
421 Returns the number of cases used in the computations."
422 (sum (if-else (send self :included) 1 0)))
424 (defmeth regression-model-proto :num-coefs ()
425 "Message args: ()
426 Returns the number of coefficients in the fit model (including the
427 intercept if the model includes one)."
428 (if (send self :intercept)
429 (+ 1 (nelts (send self :basis)))
430 (nelts (send self :basis))))
432 (defmeth regression-model-proto :df ()
433 "Message args: ()
434 Returns the number of degrees of freedom in the model."
435 (- (send self :num-included) (send self :num-coefs)))
437 (defmeth regression-model-proto :x-matrix ()
438 "Message args: ()
439 Returns the X matrix for the model, including a column of 1's, if
440 appropriate. Columns of X matrix correspond to entries in basis."
441 (let ((m (select (send self :x)
442 (iseq 0 (- (send self :num-cases) 1))
443 (send self :basis))))
444 (if (send self :intercept)
445 (bind2 (repeat 1 (send self :num-cases)) m)
446 m)))
448 (defmeth regression-model-proto :leverages ()
449 "Message args: ()
450 Returns the diagonal elements of the hat matrix."
451 (let* ((weights (send self :weights))
452 (x (send self :x-matrix))
453 (raw-levs
454 (m* (* (m* x (send self :xtxinv)) x)
455 (repeat 1 (send self :num-coefs)))))
456 (if weights (* weights raw-levs) raw-levs)))
458 (defmeth regression-model-proto :fit-values ()
459 "Message args: ()
460 Returns the fitted values for the model."
461 (m* (send self :x-matrix) (send self :coef-estimates)))
463 (defmeth regression-model-proto :raw-residuals ()
464 "Message args: ()
465 Returns the raw residuals for a model."
466 (- (send self :y) (send self :fit-values)))
468 (defmeth regression-model-proto :residuals ()
469 "Message args: ()
470 Returns the raw residuals for a model without weights. If the model
471 includes weights the raw residuals times the square roots of the weights
472 are returned."
473 (let ((raw-residuals (send self :raw-residuals))
474 (weights (send self :weights)))
475 (if weights (* (sqrt weights) raw-residuals) raw-residuals)))
477 (defmeth regression-model-proto :sum-of-squares ()
478 "Message args: ()
479 Returns the error sum of squares for the model."
480 (send self :residual-sum-of-squares))
482 (defmeth regression-model-proto :sigma-hat ()
483 "Message args: ()
484 Returns the estimated standard deviation of the deviations about the
485 regression line."
486 (let ((ss (send self :sum-of-squares))
487 (df (send self :df)))
488 (if (/= df 0) (sqrt (/ ss df)))))
490 ;; for models without an intercept the 'usual' formula for R^2 can give
491 ;; negative results; hence the max.
492 (defmeth regression-model-proto :r-squared ()
493 "Message args: ()
494 Returns the sample squared multiple correlation coefficient, R squared, for
495 the regression."
496 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
499 (defmeth regression-model-proto :coef-estimates ()
500 "Message args: ()
502 Returns the OLS (ordinary least squares) estimates of the regression
503 coefficients. Entries beyond the intercept correspond to entries in
504 basis."
505 (let ((n (array-dimension (send self :x) 1))
506 (indices (flatten-list
507 (if (send self :intercept)
508 (cons 0 (+ 1 (send self :basis)))
509 (list (+ 1 (send self :basis))))))
510 (m (send self :sweep-matrix)))
511 (format t "~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
512 m n indices (send self :basis))
513 (coerce (compound-data-seq (select m (+ 1 n) indices)) 'list))) ;; ERROR
515 (defmeth regression-model-proto :xtxinv ()
516 "Message args: ()
517 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
518 (let ((indices (if (send self :intercept)
519 (cons 0 (1+ (send self :basis)))
520 (1+ (send self :basis)))))
521 (select (send self :sweep-matrix) indices indices)))
523 (defmeth regression-model-proto :coef-standard-errors ()
524 "Message args: ()
525 Returns estimated standard errors of coefficients. Entries beyond the
526 intercept correspond to entries in basis."
527 (let ((s (send self :sigma-hat)))
528 (if s (* (send self :sigma-hat) (sqrt (diagonalf (send self :xtxinv)))))))
530 (defmeth regression-model-proto :studentized-residuals ()
531 "Message args: ()
532 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
533 (let ((res (send self :residuals))
534 (lev (send self :leverages))
535 (sig (send self :sigma-hat))
536 (inc (send self :included)))
537 (if-else inc
538 (/ res (* sig (sqrt (pmax .00001 (- 1 lev)))))
539 (/ res (* sig (sqrt (+ 1 lev)))))))
541 (defmeth regression-model-proto :externally-studentized-residuals ()
542 "Message args: ()
543 Computes the externally studentized residuals."
544 (let* ((res (send self :studentized-residuals))
545 (df (send self :df)))
546 (if-else (send self :included)
547 (* res (sqrt (/ (- df 1) (- df (^ res 2)))))
548 res)))
550 (defmeth regression-model-proto :cooks-distances ()
551 "Message args: ()
552 Computes Cook's distances."
553 (let ((lev (send self :leverages))
554 (res (/ (^ (send self :studentized-residuals) 2)
555 (send self :num-coefs))))
556 (if-else (send self :included) (* res (/ lev (- 1 lev) )) (* res lev))))
559 (defun plot-points (x y &rest args)
560 "need to fix."
561 (declare (ignore x y args))
562 (error "Graphics not implemented yet."))
564 ;; Can not plot points yet!!
565 (defmeth regression-model-proto :plot-residuals (&optional x-values)
566 "Message args: (&optional x-values)
567 Opens a window with a plot of the residuals. If X-VALUES are not supplied
568 the fitted values are used. The plot can be linked to other plots with the
569 link-views function. Returns a plot object."
570 (plot-points (if x-values x-values (send self :fit-values))
571 (send self :residuals)
572 :title "Residual Plot"
573 :point-labels (send self :case-labels)))
575 (defmeth regression-model-proto :plot-bayes-residuals
576 (&optional x-values)
577 "Message args: (&optional x-values)
579 Opens a window with a plot of the standardized residuals and two
580 standard error bars for the posterior distribution of the actual
581 deviations from the line. See Chaloner and Brant. If X-VALUES are not
582 supplied the fitted values are used. The plot can be linked to other
583 plots with the link-views function. Returns a plot object."
585 (let* ((r (/ (send self :residuals)
586 (send self :sigma-hat)))
587 (d (* 2 (sqrt (send self :leverages))))
588 (low (- r d))
589 (high (+ r d))
590 (x-values (if x-values x-values (send self :fit-values)))
591 (p (plot-points x-values r
592 :title "Bayes Residual Plot"
593 :point-labels (send self :case-labels))))
594 (map 'list #'(lambda (a b c d) (send p :plotline a b c d nil))
595 x-values low x-values high)
596 (send p :adjust-to-data)