STARTING LISP-MATRIX SWAP IN! NEXT FEW EONS! ALL IS BROKEN!
[CommonLispStat.git] / src / stat-models / regression.lsp
blobf4affe08ae309aeb18a6358de396502b362bab7b
1 ;;; -*- mode: lisp -*-
2 ;;;
3 ;;; Copyright (c) 2005--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 (in-package :lisp-stat-regression-linear)
19 ;;; Regresion Model Prototype
21 ;; The general strategy behind the fitting of models using prototypes
22 ;; is that we need to think about want the actual fits are, and then
23 ;; the fits can be used to recompute as components are changes. One
24 ;; catch here is that we'd like some notion of trace-ability, in
25 ;; particular, there is not necessarily a fixed way to take care of the
26 ;; audit trail. save-and-die might be a means of recording the final
27 ;; approach, but we are challenged by the problem of using advice and
28 ;; other such features to capture stages and steps that are considered
29 ;; along the goals of estimating a model.
31 ;; Note that the above is a stream-of-conscience response to the
32 ;; challenge of reproducibility in the setting of prototype "on-line"
33 ;; computation.
35 (defvar regression-model-proto nil
36 "Prototype for all regression model instances.")
37 (defproto regression-model-proto
38 '(x y intercept sweep-matrix basis weights
39 included
40 total-sum-of-squares
41 residual-sum-of-squares
42 predictor-names
43 response-name
44 case-labels
45 doc)
47 *object*
48 "Normal Linear Regression Model")
51 (defun regression-model (x y &key
52 (intercept T)
53 (print T)
54 (weights nil)
55 (included (repeat t (length y)))
56 predictor-names
57 response-name
58 case-labels
59 (doc "Undocumented Regression Model Instance")
60 (debug T))
61 "Args: (x y &key (intercept T) (print T) (weights nil)
62 included predictor-names response-name case-labels)
63 X - list of independent variables or X matrix
64 Y - dependent variable.
65 INTERCEPT - T to include (default), NIL for no intercept
66 PRINT - if not NIL print summary information
67 WEIGHTS - if supplied should be the same length as Y; error
68 variances are
69 assumed to be inversely proportional to WEIGHTS
70 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
71 - sequences of strings or symbols.
72 INCLUDED - if supplied should be the same length as Y, with
73 elements nil to skip a in computing estimates (but not
74 in residual analysis).
75 Returns a regression model object. To examine the model further assign the
76 result to a variable and send it messages.
77 Example (data are in file absorbtion.lsp in the sample data directory):
78 (def m (regression-model (list iron aluminum) absorbtion))
79 (send m :help) (send m :plot-residuals)"
80 (let ((x (cond
81 ((matrixp x) x)
82 ((typep x 'vector) (list x))
83 ((and (consp x)
84 (numberp (car x))) (list x))
85 (t x)))
86 (m (send regression-model-proto :new)))
87 (format t "~%")
88 (send m :doc doc)
89 (send m :x (if (matrixp x) x (apply #'bind-columns x)))
90 (send m :y y)
91 (send m :intercept intercept)
92 (send m :weights weights)
93 (send m :included included)
94 (send m :predictor-names predictor-names)
95 (send m :response-name response-name)
96 (send m :case-labels case-labels)
97 (if debug
98 (progn
99 (format t "~%")
100 (format t "~S~%" (send m :doc))
101 (format t "X: ~S~%" (send m :x))
102 (format t "Y: ~S~%" (send m :y))))
103 (if print (send m :display))
106 (defmeth regression-model-proto :isnew ()
107 (send self :needs-computing t))
109 (defmeth regression-model-proto :save ()
110 "Message args: ()
111 Returns an expression that will reconstruct the regression model."
112 `(regression-model ',(send self :x)
113 ',(send self :y)
114 :intercept ',(send self :intercept)
115 :weights ',(send self :weights)
116 :included ',(send self :included)
117 :predictor-names ',(send self :predictor-names)
118 :response-name ',(send self :response-name)
119 :case-labels ',(send self :case-labels)))
121 ;;; Computing and Display Methods
123 (defmeth regression-model-proto :compute ()
124 "Message args: ()
125 Recomputes the estimates. For internal use by other messages"
126 (let* ((included (if-else (send self :included) 1 0))
127 (x (send self :x))
128 (y (send self :y))
129 (intercept (send self :intercept))
130 (weights (send self :weights))
131 (w (if weights (* included weights) included))
132 (m (make-sweep-matrix x y w)) ;;; ERROR HERE
133 (n (array-dimension x 1))
134 (p (- (array-dimension m 0) 1))
135 (tss (aref m p p))
136 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation (column-list x)))))
137 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
138 (sweep-result
139 (if intercept
140 (sweep-operator m (iseq 1 n) tol)
141 (sweep-operator m (iseq 0 n) (cons 0.0 tol)))))
142 (format t
143 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
144 sweep-result x y m tss)
145 (setf (slot-value 'sweep-matrix) (first sweep-result))
146 (setf (slot-value 'total-sum-of-squares) tss)
147 (setf (slot-value 'residual-sum-of-squares)
148 (aref (first sweep-result) p p))
149 ;; SOMETHING WRONG HERE! FIX-ME
150 (setf (slot-value 'basis)
151 (let ((b (remove 0 (second sweep-result))))
152 (if b (- (reduce #'- (reverse b)) 1)
153 (error "no columns could be swept"))))))
155 (defmeth regression-model-proto :needs-computing (&optional set)
156 "Message args: ( &optional set )
158 If value given, sets the flag for whether (re)computation is needed to
159 update the model fits."
160 (send self :nop)
161 (if set (setf (slot-value 'sweep-matrix) nil))
162 (null (slot-value 'sweep-matrix)))
164 (defmeth regression-model-proto :display ()
165 "Message args: ()
167 Prints the least squares regression summary. Variables not used in the fit
168 are marked as aliased."
169 (let ((coefs (coerce (send self :coef-estimates) 'list))
170 (se-s (send self :coef-standard-errors))
171 (x (send self :x))
172 (p-names (send self :predictor-names)))
173 (if (send self :weights)
174 (format t "~%Weighted Least Squares Estimates:~2%")
175 (format t "~%Least Squares Estimates:~2%"))
176 (when (send self :intercept)
177 (format t "Constant ~10f ~A~%"
178 (car coefs) (list (car se-s)))
179 (setf coefs (cdr coefs))
180 (setf se-s (cdr se-s)))
181 (dotimes (i (array-dimension x 1))
182 (cond
183 ((member i (send self :basis))
184 (format t "~22a ~10f ~A~%"
185 (select p-names i) (car coefs) (list (car se-s)))
186 (setf coefs (cdr coefs) se-s (cdr se-s)))
187 (t (format t "~22a aliased~%" (select p-names i)))))
188 (format t "~%")
189 (format t "R Squared: ~10f~%" (send self :r-squared))
190 (format t "Sigma hat: ~10f~%" (send self :sigma-hat))
191 (format t "Number of cases: ~10d~%" (send self :num-cases))
192 (if (/= (send self :num-cases) (send self :num-included))
193 (format t "Number of cases used: ~10d~%" (send self :num-included)))
194 (format t "Degrees of freedom: ~10d~%" (send self :df))
195 (format t "~%")))
197 ;;; Slot accessors and mutators
199 (defmeth regression-model-proto :doc (&optional new-doc append)
200 "Message args: (&optional new-doc)
202 Returns the DOC-STRING as supplied to m.
203 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
204 NEW-DOC. In this setting, when APPEND is T, append NEW-DOC to DOC
205 rather than doing replacement."
206 (send self :nop)
207 (when (and new-doc (stringp new-doc))
208 (setf (slot-value 'doc)
209 (if append
210 (concatenate 'string
211 (slot-value 'doc)
212 new-doc)
213 new-doc)))
214 (slot-value 'doc))
217 (defmeth regression-model-proto :x (&optional new-x)
218 "Message args: (&optional new-x)
220 With no argument returns the x matrix as supplied to m. With an
221 argument, NEW-X sets the x matrix to NEW-X and recomputes the
222 estimates."
223 (when (and new-x (matrixp new-x))
224 (setf (slot-value 'x) new-x)
225 (send self :needs-computing t))
226 (slot-value 'x))
228 (defmeth regression-model-proto :y (&optional new-y)
229 "Message args: (&optional new-y)
231 With no argument returns the y sequence as supplied to m. With an
232 argument, NEW-Y sets the y sequence to NEW-Y and recomputes the
233 estimates."
234 (when (and new-y
235 (or (matrixp new-y)
236 (typep new-y 'sequence)))
237 (setf (slot-value 'y) new-y)
238 (send self :needs-computing t))
239 (slot-value 'y))
241 (defmeth regression-model-proto :intercept (&optional (val nil set))
242 "Message args: (&optional new-intercept)
244 With no argument returns T if the model includes an intercept term,
245 nil if not. With an argument NEW-INTERCEPT the model is changed to
246 include or exclude an intercept, according to the value of
247 NEW-INTERCEPT."
248 (when set
249 (setf (slot-value 'intercept) val)
250 (send self :needs-computing t))
251 (slot-value 'intercept))
253 (defmeth regression-model-proto :weights (&optional (new-w nil set))
254 "Message args: (&optional new-w)
256 With no argument returns the weight sequence as supplied to m; NIL
257 means an unweighted model. NEW-W sets the weights sequence to NEW-W
258 and recomputes the estimates."
259 (when set
260 (setf (slot-value 'weights) new-w)
261 (send self :needs-computing t))
262 (slot-value 'weights))
264 (defmeth regression-model-proto :total-sum-of-squares ()
265 "Message args: ()
267 Returns the total sum of squares around the mean."
268 (if (send self :needs-computing) (send self :compute))
269 (slot-value 'total-sum-of-squares))
271 (defmeth regression-model-proto :residual-sum-of-squares ()
272 "Message args: ()
274 Returns the residual sum of squares for the model."
275 (if (send self :needs-computing) (send self :compute))
276 (slot-value 'residual-sum-of-squares))
278 (defmeth regression-model-proto :basis ()
279 "Message args: ()
281 Returns the indices of the variables used in fitting the model, in a
282 sequence. Recompute before this, if needed."
283 (if (send self :needs-computing)
284 (send self :compute))
285 (if (typep (slot-value 'basis) 'sequence)
286 (slot-value 'basis)
287 (list (slot-value 'basis))))
290 (defmeth regression-model-proto :sweep-matrix ()
291 "Message args: ()
293 Returns the swept sweep matrix. For internal use"
294 (if (send self :needs-computing)
295 (send self :compute))
296 (slot-value 'sweep-matrix))
298 (defmeth regression-model-proto :included (&optional new-included)
299 "Message args: (&optional new-included)
301 With no argument, NIL means a case is not used in calculating
302 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
303 of length of y of nil and t to select cases. Estimates are
304 recomputed."
305 (when (and new-included
306 (= (length new-included) (send self :num-cases)))
307 (setf (slot-value 'included) (copy-seq new-included))
308 (send self :needs-computing t))
309 (if (slot-value 'included)
310 (slot-value 'included)
311 (repeat t (send self :num-cases))))
313 (defmeth regression-model-proto :predictor-names (&optional (names nil set))
314 "Message args: (&optional (names nil set))
316 With no argument returns the predictor names. NAMES sets the names."
317 (if set (setf (slot-value 'predictor-names) (mapcar #'string names)))
318 (let ((p (array-dimension (send self :x) 1))
319 (p-names (slot-value 'predictor-names)))
320 (if (not (and p-names (= (length p-names) p)))
321 (setf (slot-value 'predictor-names)
322 (mapcar #'(lambda (a) (format nil "Variable ~a" a))
323 (iseq 0 (- p 1))))))
324 (slot-value 'predictor-names))
326 (defmeth regression-model-proto :response-name (&optional (name "Y" set))
327 "Message args: (&optional name)
329 With no argument returns the response name. NAME sets the name."
330 (send self :nop)
331 (if set (setf (slot-value 'response-name) (if name (string name) "Y")))
332 (slot-value 'response-name))
334 (defmeth regression-model-proto :case-labels (&optional (labels nil set))
335 "Message args: (&optional labels)
336 With no argument returns the case-labels. LABELS sets the labels."
337 (if set (setf (slot-value 'case-labels)
338 (if labels
339 (mapcar #'string labels)
340 (mapcar #'(lambda (x) (format nil "~d" x))
341 (iseq 0 (- (send self :num-cases) 1))))))
342 (slot-value 'case-labels))
345 ;;; Other Methods
346 ;;; None of these methods access any slots directly.
349 (defmeth regression-model-proto :num-cases ()
350 "Message args: ()
351 Returns the number of cases in the model."
352 (length (send self :y)))
354 (defmeth regression-model-proto :num-included ()
355 "Message args: ()
356 Returns the number of cases used in the computations."
357 (sum (if-else (send self :included) 1 0)))
359 (defmeth regression-model-proto :num-coefs ()
360 "Message args: ()
361 Returns the number of coefficients in the fit model (including the
362 intercept if the model includes one)."
363 (if (send self :intercept)
364 (+ 1 (length (send self :basis)))
365 (length (send self :basis))))
367 (defmeth regression-model-proto :df ()
368 "Message args: ()
369 Returns the number of degrees of freedom in the model."
370 (- (send self :num-included) (send self :num-coefs)))
372 (defmeth regression-model-proto :x-matrix ()
373 "Message args: ()
374 Returns the X matrix for the model, including a column of 1's, if
375 appropriate. Columns of X matrix correspond to entries in basis."
376 (let ((m (select (send self :x)
377 (iseq 0 (- (send self :num-cases) 1))
378 (send self :basis))))
379 (if (send self :intercept)
380 (bind-columns (repeat 1 (send self :num-cases)) m)
381 m)))
383 (defmeth regression-model-proto :leverages ()
384 "Message args: ()
385 Returns the diagonal elements of the hat matrix."
386 (let* ((weights (send self :weights))
387 (x (send self :x-matrix))
388 (raw-levs
389 (matmult (* (matmult x (send self :xtxinv)) x)
390 (repeat 1 (send self :num-coefs)))))
391 (if weights (* weights raw-levs) raw-levs)))
393 (defmeth regression-model-proto :fit-values ()
394 "Message args: ()
395 Returns the fitted values for the model."
396 (matmult (send self :x-matrix) (send self :coef-estimates)))
398 (defmeth regression-model-proto :raw-residuals ()
399 "Message args: ()
400 Returns the raw residuals for a model."
401 (- (send self :y) (send self :fit-values)))
403 (defmeth regression-model-proto :residuals ()
404 "Message args: ()
405 Returns the raw residuals for a model without weights. If the model
406 includes weights the raw residuals times the square roots of the weights
407 are returned."
408 (let ((raw-residuals (send self :raw-residuals))
409 (weights (send self :weights)))
410 (if weights (* (sqrt weights) raw-residuals) raw-residuals)))
412 (defmeth regression-model-proto :sum-of-squares ()
413 "Message args: ()
414 Returns the error sum of squares for the model."
415 (send self :residual-sum-of-squares))
417 (defmeth regression-model-proto :sigma-hat ()
418 "Message args: ()
419 Returns the estimated standard deviation of the deviations about the
420 regression line."
421 (let ((ss (send self :sum-of-squares))
422 (df (send self :df)))
423 (if (/= df 0) (sqrt (/ ss df)))))
425 ;; for models without an intercept the 'usual' formula for R^2 can give
426 ;; negative results; hence the max.
427 (defmeth regression-model-proto :r-squared ()
428 "Message args: ()
429 Returns the sample squared multiple correlation coefficient, R squared, for
430 the regression."
431 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
434 (defmeth regression-model-proto :coef-estimates ()
435 "Message args: ()
437 Returns the OLS (ordinary least squares) estimates of the regression
438 coefficients. Entries beyond the intercept correspond to entries in
439 basis."
440 (let ((n (array-dimension (send self :x) 1))
441 (indices (flatten-list
442 (if (send self :intercept)
443 (cons 0 (+ 1 (send self :basis)))
444 (list (+ 1 (send self :basis))))))
445 (m (send self :sweep-matrix)))
446 (format t "~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
447 m n indices (send self :basis))
448 (coerce (compound-data-seq (select m (+ 1 n) indices)) 'list))) ;; ERROR
450 (defmeth regression-model-proto :xtxinv ()
451 "Message args: ()
452 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
453 (let ((indices (if (send self :intercept)
454 (cons 0 (1+ (send self :basis)))
455 (1+ (send self :basis)))))
456 (select (send self :sweep-matrix) indices indices)))
458 (defmeth regression-model-proto :coef-standard-errors ()
459 "Message args: ()
460 Returns estimated standard errors of coefficients. Entries beyond the
461 intercept correspond to entries in basis."
462 (let ((s (send self :sigma-hat)))
463 (if s (* (send self :sigma-hat) (sqrt (diagonal (send self :xtxinv)))))))
465 (defmeth regression-model-proto :studentized-residuals ()
466 "Message args: ()
467 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
468 (let ((res (send self :residuals))
469 (lev (send self :leverages))
470 (sig (send self :sigma-hat))
471 (inc (send self :included)))
472 (if-else inc
473 (/ res (* sig (sqrt (pmax .00001 (- 1 lev)))))
474 (/ res (* sig (sqrt (+ 1 lev)))))))
476 (defmeth regression-model-proto :externally-studentized-residuals ()
477 "Message args: ()
478 Computes the externally studentized residuals."
479 (let* ((res (send self :studentized-residuals))
480 (df (send self :df)))
481 (if-else (send self :included)
482 (* res (sqrt (/ (- df 1) (- df (^ res 2)))))
483 res)))
485 (defmeth regression-model-proto :cooks-distances ()
486 "Message args: ()
487 Computes Cook's distances."
488 (let ((lev (send self :leverages))
489 (res (/ (^ (send self :studentized-residuals) 2)
490 (send self :num-coefs))))
491 (if-else (send self :included) (* res (/ lev (- 1 lev) )) (* res lev))))
494 (defun plot-points (x y &rest args)
495 "need to fix."
496 (declare (ignore x y args))
497 (error "Graphics not implemented yet."))
499 ;; Can not plot points yet!!
500 (defmeth regression-model-proto :plot-residuals (&optional x-values)
501 "Message args: (&optional x-values)
502 Opens a window with a plot of the residuals. If X-VALUES are not supplied
503 the fitted values are used. The plot can be linked to other plots with the
504 link-views function. Returns a plot object."
505 (plot-points (if x-values x-values (send self :fit-values))
506 (send self :residuals)
507 :title "Residual Plot"
508 :point-labels (send self :case-labels)))
510 (defmeth regression-model-proto :plot-bayes-residuals
511 (&optional x-values)
512 "Message args: (&optional x-values)
514 Opens a window with a plot of the standardized residuals and two
515 standard error bars for the posterior distribution of the actual
516 deviations from the line. See Chaloner and Brant. If X-VALUES are not
517 supplied the fitted values are used. The plot can be linked to other
518 plots with the link-views function. Returns a plot object."
520 (let* ((r (/ (send self :residuals)
521 (send self :sigma-hat)))
522 (d (* 2 (sqrt (send self :leverages))))
523 (low (- r d))
524 (high (+ r d))
525 (x-values (if x-values x-values (send self :fit-values)))
526 (p (plot-points x-values r
527 :title "Bayes Residual Plot"
528 :point-labels (send self :case-labels))))
529 (map 'list #'(lambda (a b c d) (send p :plotline a b c d nil))
530 x-values low x-values high)
531 (send p :adjust-to-data)