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