remove sweep op, and start prep'ing a QR based approach.
[CommonLispStat.git] / src / stat-models / regression.lisp
blob1245fac1b4bef4fe855d921b533022d0416db6bc
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 (send :beta-coefficents (lm x y))
171 (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...
179 (tol (* 0.001
180 (reduce #'* (mapcar #'standard-deviation
181 (list-of-columns x))))))
182 (format t
183 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
184 sweep-result x y m tss)
185 (setf (slot-value 'sweep-matrix) (first sweep-result))
186 (setf (slot-value 'total-sum-of-squares) tss)
187 (setf (slot-value 'residual-sum-of-squares)
188 (mref (first sweep-result) p p))
189 ;; SOMETHING WRONG HERE! FIX-ME
190 (setf (slot-value 'basis)
191 (let ((b (remove 0 (second sweep-result))))
192 (if b (- (reduce #'- (reverse b)) 1)
193 (error "no columns could be swept"))))))
195 (defmeth regression-model-proto :needs-computing (&optional set)
196 "Message args: ( &optional set )
198 If value given, sets the flag for whether (re)computation is needed to
199 update the model fits."
200 (send self :nop)
201 (if set (setf (slot-value 'sweep-matrix) nil))
202 (null (slot-value 'sweep-matrix)))
204 (defmeth regression-model-proto :display ()
205 "Message args: ()
207 Prints the least squares regression summary. Variables not used in the fit
208 are marked as aliased."
209 (let ((coefs (coerce (send self :coef-estimates) 'list))
210 (se-s (send self :coef-standard-errors))
211 (x (send self :x))
212 (p-names (send self :predictor-names)))
213 (if (send self :weights)
214 (format t "~%Weighted Least Squares Estimates:~2%")
215 (format t "~%Least Squares Estimates:~2%"))
216 (when (send self :intercept)
217 (format t "Constant ~10f ~A~%"
218 (car coefs) (list (car se-s)))
219 (setf coefs (cdr coefs))
220 (setf se-s (cdr se-s)))
221 (dotimes (i (array-dimension x 1))
222 (cond
223 ((member i (send self :basis))
224 (format t "~22a ~10f ~A~%"
225 (select p-names i) (car coefs) (list (car se-s)))
226 (setf coefs (cdr coefs) se-s (cdr se-s)))
227 (t (format t "~22a aliased~%" (select p-names i)))))
228 (format t "~%")
229 (format t "R Squared: ~10f~%" (send self :r-squared))
230 (format t "Sigma hat: ~10f~%" (send self :sigma-hat))
231 (format t "Number of cases: ~10d~%" (send self :num-cases))
232 (if (/= (send self :num-cases) (send self :num-included))
233 (format t "Number of cases used: ~10d~%" (send self :num-included)))
234 (format t "Degrees of freedom: ~10d~%" (send self :df))
235 (format t "~%")))
237 ;;; Slot accessors and mutators
239 (defmeth regression-model-proto :doc (&optional new-doc append)
240 "Message args: (&optional new-doc)
242 Returns the DOC-STRING as supplied to m.
243 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
244 NEW-DOC. In this setting, when APPEND is T, don't replace and just
245 append NEW-DOC to DOC."
246 (send self :nop)
247 (when (and new-doc (stringp new-doc))
248 (setf (slot-value 'doc)
249 (if append
250 (concatenate 'string
251 (slot-value 'doc)
252 new-doc)
253 new-doc)))
254 (slot-value 'doc))
257 (defmeth regression-model-proto :x (&optional new-x)
258 "Message args: (&optional new-x)
260 With no argument returns the x matrix-like as supplied to m. With an
261 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
262 estimates."
263 (when (and new-x (typep new-x 'matrix-like))
264 (setf (slot-value 'x) new-x)
265 (send self :needs-computing t))
266 (slot-value 'x))
268 (defmeth regression-model-proto :y (&optional new-y)
269 "Message args: (&optional new-y)
271 With no argument returns the y vector-like as supplied to m. With an
272 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
273 estimates."
274 (when (and new-y
275 (typep new-y 'vector-like))
276 (setf (slot-value 'y) new-y) ;; fixme -- pls set slot value to a vector-like!
277 (send self :needs-computing t))
278 (slot-value 'y))
280 (defmeth regression-model-proto :intercept (&optional (val nil set))
281 "Message args: (&optional new-intercept)
283 With no argument returns T if the model includes an intercept term,
284 nil if not. With an argument NEW-INTERCEPT the model is changed to
285 include or exclude an intercept, according to the value of
286 NEW-INTERCEPT."
287 (when set
288 (setf (slot-value 'intercept) val)
289 (send self :needs-computing t))
290 (slot-value 'intercept))
292 (defmeth regression-model-proto :weights (&optional (new-w nil set))
293 "Message args: (&optional new-w)
295 With no argument returns the weight vector-like as supplied to m; NIL
296 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
297 and recomputes the estimates."
298 (when (and set nil
299 (or (= new-w nil)
300 (typep new-w 'vector-like)))
301 (setf (slot-value 'weights) new-w)
302 (send self :needs-computing t))
303 (slot-value 'weights))
305 (defmeth regression-model-proto :total-sum-of-squares ()
306 "Message args: ()
308 Returns the total sum of squares around the mean.
309 This is recomputed if an update is needed."
310 (if (send self :needs-computing)
311 (send self :compute))
312 (slot-value 'total-sum-of-squares))
314 (defmeth regression-model-proto :residual-sum-of-squares ()
315 "Message args: ()
317 Returns the residual sum of squares for the model.
318 This is recomputed if an update is needed."
319 (if (send self :needs-computing)
320 (send self :compute))
321 (slot-value 'residual-sum-of-squares))
323 (defmeth regression-model-proto :basis ()
324 "Message args: ()
326 Returns the indices of the variables used in fitting the model, in a
327 sequence.
328 This is recomputed if an update is needed."
329 (if (send self :needs-computing)
330 (send self :compute))
331 (slot-value 'basis))
333 (defmeth regression-model-proto :included (&optional new-included)
334 "Message args: (&optional new-included)
336 With no argument, NIL means a case is not used in calculating
337 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
338 of length of y of nil and t to select cases. Estimates are
339 recomputed."
340 (when (and new-included
341 (= (length new-included) (send self :num-cases)))
342 (setf (slot-value 'included) (copy-seq new-included))
343 (send self :needs-computing t))
344 (if (slot-value 'included)
345 (slot-value 'included)
346 (repeat t (send self :num-cases))))
348 (defmeth regression-model-proto :predictor-names (&optional (names nil set))
349 "Message args: (&optional (names nil set))
351 With no argument returns the predictor names. NAMES sets the names."
352 (if set (setf (slot-value 'predictor-names) (mapcar #'string names)))
353 (let ((p (matrix-dimension (send self :x) 1))
354 (p-names (slot-value 'predictor-names)))
355 (if (not (and p-names (= (length p-names) p)))
356 (setf (slot-value 'predictor-names)
357 (mapcar #'(lambda (a) (format nil "Variable ~a" a))
358 (iseq 0 (- p 1))))))
359 (slot-value 'predictor-names))
361 (defmeth regression-model-proto :response-name (&optional (name "Y" set))
362 "Message args: (&optional name)
364 With no argument returns the response name. NAME sets the name."
365 (send self :nop)
366 (if set (setf (slot-value 'response-name) (if name (string name) "Y")))
367 (slot-value 'response-name))
369 (defmeth regression-model-proto :case-labels (&optional (labels nil set))
370 "Message args: (&optional labels)
371 With no argument returns the case-labels. LABELS sets the labels."
372 (if set (setf (slot-value 'case-labels)
373 (if labels
374 (mapcar #'string labels)
375 (mapcar #'(lambda (x) (format nil "~d" x))
376 (iseq 0 (- (send self :num-cases) 1))))))
377 (slot-value 'case-labels))
380 ;;; Other Methods
381 ;;; None of these methods access any slots directly.
384 (defmeth regression-model-proto :num-cases ()
385 "Message args: ()
386 Returns the number of cases in the model."
387 (nelts (send self :y)))
389 (defmeth regression-model-proto :num-included ()
390 "Message args: ()
391 Returns the number of cases used in the computations."
392 (sum (if-else (send self :included) 1 0)))
394 (defmeth regression-model-proto :num-coefs ()
395 "Message args: ()
396 Returns the number of coefficients in the fit model (including the
397 intercept if the model includes one)."
398 (if (send self :intercept)
399 (+ 1 (nelts (send self :basis)))
400 (nelts (send self :basis))))
402 (defmeth regression-model-proto :df ()
403 "Message args: ()
404 Returns the number of degrees of freedom in the model."
405 (- (send self :num-included) (send self :num-coefs)))
407 (defmeth regression-model-proto :x-matrix ()
408 "Message args: ()
409 Returns the X matrix for the model, including a column of 1's, if
410 appropriate. Columns of X matrix correspond to entries in basis."
411 (let ((m (select (send self :x)
412 (iseq 0 (- (send self :num-cases) 1))
413 (send self :basis))))
414 (if (send self :intercept)
415 (bind2 (repeat 1 (send self :num-cases)) m)
416 m)))
418 (defmeth regression-model-proto :leverages ()
419 "Message args: ()
420 Returns the diagonal elements of the hat matrix."
421 (let* ((weights (send self :weights))
422 (x (send self :x-matrix))
423 (raw-levs
424 (m* (* (m* x (send self :xtxinv)) x)
425 (repeat 1 (send self :num-coefs)))))
426 (if weights (* weights raw-levs) raw-levs)))
428 (defmeth regression-model-proto :fit-values ()
429 "Message args: ()
430 Returns the fitted values for the model."
431 (m* (send self :x-matrix) (send self :coef-estimates)))
433 (defmeth regression-model-proto :raw-residuals ()
434 "Message args: ()
435 Returns the raw residuals for a model."
436 (- (send self :y) (send self :fit-values)))
438 (defmeth regression-model-proto :residuals ()
439 "Message args: ()
440 Returns the raw residuals for a model without weights. If the model
441 includes weights the raw residuals times the square roots of the weights
442 are returned."
443 (let ((raw-residuals (send self :raw-residuals))
444 (weights (send self :weights)))
445 (if weights (* (sqrt weights) raw-residuals) raw-residuals)))
447 (defmeth regression-model-proto :sum-of-squares ()
448 "Message args: ()
449 Returns the error sum of squares for the model."
450 (send self :residual-sum-of-squares))
452 (defmeth regression-model-proto :sigma-hat ()
453 "Message args: ()
454 Returns the estimated standard deviation of the deviations about the
455 regression line."
456 (let ((ss (send self :sum-of-squares))
457 (df (send self :df)))
458 (if (/= df 0) (sqrt (/ ss df)))))
460 ;; for models without an intercept the 'usual' formula for R^2 can give
461 ;; negative results; hence the max.
462 (defmeth regression-model-proto :r-squared ()
463 "Message args: ()
464 Returns the sample squared multiple correlation coefficient, R squared, for
465 the regression."
466 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
469 (defmeth regression-model-proto :coef-estimates ()
470 "Message args: ()
472 Returns the OLS (ordinary least squares) estimates of the regression
473 coefficients. Entries beyond the intercept correspond to entries in
474 basis."
475 (let ((n (matrix-dimension (send self :x) 1))
476 (indices (flatten-list
477 (if (send self :intercept)
478 (cons 0 (+ 1 (send self :basis)))
479 (list (+ 1 (send self :basis))))))
480 (m (send self :sweep-matrix)))
481 (format t "~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
482 m n indices (send self :basis))
483 (coerce (compound-data-seq (select m (1+ n) indices)) 'list))) ;; ERROR
485 (defmeth regression-model-proto :xtxinv ()
486 "Message args: ()
487 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
488 (let ((indices (if (send self :intercept)
489 (cons 0 (1+ (send self :basis)))
490 (1+ (send self :basis)))))
491 (select (send self :sweep-matrix) indices indices)))
493 (defmeth regression-model-proto :coef-standard-errors ()
494 "Message args: ()
495 Returns estimated standard errors of coefficients. Entries beyond the
496 intercept correspond to entries in basis."
497 (let ((s (send self :sigma-hat)))
498 (if s (* (send self :sigma-hat) (sqrt (diagonalf (send self :xtxinv)))))))
500 (defmeth regression-model-proto :studentized-residuals ()
501 "Message args: ()
502 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
503 (let ((res (send self :residuals))
504 (lev (send self :leverages))
505 (sig (send self :sigma-hat))
506 (inc (send self :included)))
507 (if-else inc
508 (/ res (* sig (sqrt (pmax .00001 (- 1 lev)))))
509 (/ res (* sig (sqrt (+ 1 lev)))))))
511 (defmeth regression-model-proto :externally-studentized-residuals ()
512 "Message args: ()
513 Computes the externally studentized residuals."
514 (let* ((res (send self :studentized-residuals))
515 (df (send self :df)))
516 (if-else (send self :included)
517 (* res (sqrt (/ (- df 1) (- df (^ res 2)))))
518 res)))
520 (defmeth regression-model-proto :cooks-distances ()
521 "Message args: ()
522 Computes Cook's distances."
523 (let ((lev (send self :leverages))
524 (res (/ (^ (send self :studentized-residuals) 2)
525 (send self :num-coefs))))
526 (if-else (send self :included) (* res (/ lev (- 1 lev) )) (* res lev))))
529 (defun plot-points (x y &rest args)
530 "need to fix."
531 (declare (ignore x y args))
532 (error "Graphics not implemented yet."))
534 ;; Can not plot points yet!!
535 (defmeth regression-model-proto :plot-residuals (&optional x-values)
536 "Message args: (&optional x-values)
537 Opens a window with a plot of the residuals. If X-VALUES are not supplied
538 the fitted values are used. The plot can be linked to other plots with the
539 link-views function. Returns a plot object."
540 (plot-points (if x-values x-values (send self :fit-values))
541 (send self :residuals)
542 :title "Residual Plot"
543 :point-labels (send self :case-labels)))
545 (defmeth regression-model-proto :plot-bayes-residuals
546 (&optional x-values)
547 "Message args: (&optional x-values)
549 Opens a window with a plot of the standardized residuals and two
550 standard error bars for the posterior distribution of the actual
551 deviations from the line. See Chaloner and Brant. If X-VALUES are not
552 supplied the fitted values are used. The plot can be linked to other
553 plots with the link-views function. Returns a plot object."
555 (let* ((r (/ (send self :residuals)
556 (send self :sigma-hat)))
557 (d (* 2 (sqrt (send self :leverages))))
558 (low (- r d))
559 (high (+ r d))
560 (x-values (if x-values x-values (send self :fit-values)))
561 (p (plot-points x-values r
562 :title "Bayes Residual Plot"
563 :point-labels (send self :case-labels))))
564 (map 'list #'(lambda (a b c d) (send p :plotline a b c d nil))
565 x-values low x-values high)
566 (send p :adjust-to-data)