STARTING LISP-MATRIX SWAP IN! NEXT FEW EONS! ALL IS BROKEN!
[CommonLispStat.git] / src / stat-models / regression-lispmat.lisp
blobf92a1f8561a1c8c7e718d02f1b602275e461b93e
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.")
39 (defproto regression-model-proto
40 '(x y intercept sweep-matrix basis weights
41 included
42 total-sum-of-squares
43 residual-sum-of-squares
44 predictor-names
45 response-name
46 case-labels
47 doc)
49 *object*
50 "Normal Linear Regression Model")
53 (defun regression-model (x y &key
54 (intercept T)
55 (print T)
56 (weights nil)
57 (included (repeat t (length y)))
58 predictor-names
59 response-name
60 case-labels
61 (doc "Undocumented Regression Model Instance")
62 (debug T))
63 "Args: (x y &key (intercept T) (print T) (weights nil)
64 included predictor-names response-name case-labels)
65 X - list of independent variables or X matrix
66 Y - dependent variable.
67 INTERCEPT - T to include (default), NIL for no intercept
68 PRINT - if not NIL print summary information
69 WEIGHTS - if supplied should be the same length as Y; error
70 variances are
71 assumed to be inversely proportional to WEIGHTS
72 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
73 - sequences of strings or symbols.
74 INCLUDED - if supplied should be the same length as Y, with
75 elements nil to skip a in computing estimates (but not
76 in residual analysis).
77 Returns a regression model object. To examine the model further assign the
78 result to a variable and send it messages.
79 Example (data are in file absorbtion.lsp in the sample data directory):
80 (def m (regression-model (list iron aluminum) absorbtion))
81 (send m :help) (send m :plot-residuals)"
82 (let ((x (cond
83 ((typep x 'matrix-like) x)
84 ((or (typep x 'vector)
85 (and (consp x)
86 (numberp (car x))) (make-vector (length x) :initial-contents x)))
87 (t x))) ;; actually, might should barf.
88 (y (cond
89 ((typep y 'vector-like) y)
90 ((and (consp x)
91 (numberp (car x))) (make-vector (length y) :initial-contents y))
92 (t y))) ;; actually, might should barf.
93 (m (send regression-model-proto :new)))
94 (format t "~%")
95 (send m :doc doc)
96 (send m :x x)
97 (send m :y y)
98 (send m :intercept intercept)
99 (send m :weights weights)
100 (send m :included included)
101 (send m :predictor-names predictor-names)
102 (send m :response-name response-name)
103 (send m :case-labels case-labels)
104 (if debug
105 (progn
106 (format t "~%")
107 (format t "~S~%" (send m :doc))
108 (format t "X: ~S~%" (send m :x))
109 (format t "Y: ~S~%" (send m :y))))
110 (if print (send m :display))
113 (defmeth regression-model-proto :isnew ()
114 (send self :needs-computing t))
116 (defmeth regression-model-proto :save ()
117 "Message args: ()
118 Returns an expression that will reconstruct the regression model."
119 `(regression-model ',(send self :x)
120 ',(send self :y)
121 :intercept ',(send self :intercept)
122 :weights ',(send self :weights)
123 :included ',(send self :included)
124 :predictor-names ',(send self :predictor-names)
125 :response-name ',(send self :response-name)
126 :case-labels ',(send self :case-labels)))
128 ;;; Computing and Display Methods
130 (defmeth regression-model-proto :compute ()
131 "Message args: ()
132 Recomputes the estimates. For internal use by other messages"
133 (let* ((included (if-else (send self :included) 1 0))
134 (x (send self :x))
135 (y (send self :y))
136 (intercept (send self :intercept))
137 (weights (send self :weights))
138 (w (if weights (* included weights) included))
139 (m (make-sweep-matrix x y w)) ;;; ERROR HERE
140 (n (matrix-dimension x 1))
141 (p (- (matrix-dimension m 0) 1))
142 (tss (mref m p p))
143 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation (column-list x)))))
144 (sweep-result
145 (if intercept
146 (sweep-operator m (iseq 1 n) tol)
147 (sweep-operator m (iseq 0 n) (cons 0.0 tol)))))
148 (format t
149 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
150 sweep-result x y m tss)
151 (setf (slot-value 'sweep-matrix) (first sweep-result))
152 (setf (slot-value 'total-sum-of-squares) tss)
153 (setf (slot-value 'residual-sum-of-squares)
154 (mref (first sweep-result) p p))
155 ;; SOMETHING WRONG HERE! FIX-ME
156 (setf (slot-value 'basis)
157 (let ((b (remove 0 (second sweep-result))))
158 (if b (- (reduce #'- (reverse b)) 1)
159 (error "no columns could be swept"))))))
161 (defmeth regression-model-proto :needs-computing (&optional set)
162 "Message args: ( &optional set )
164 If value given, sets the flag for whether (re)computation is needed to
165 update the model fits."
166 (send self :nop)
167 (if set (setf (slot-value 'sweep-matrix) nil))
168 (null (slot-value 'sweep-matrix)))
170 (defmeth regression-model-proto :display ()
171 "Message args: ()
173 Prints the least squares regression summary. Variables not used in the fit
174 are marked as aliased."
175 (let ((coefs (coerce (send self :coef-estimates) 'list))
176 (se-s (send self :coef-standard-errors))
177 (x (send self :x))
178 (p-names (send self :predictor-names)))
179 (if (send self :weights)
180 (format t "~%Weighted Least Squares Estimates:~2%")
181 (format t "~%Least Squares Estimates:~2%"))
182 (when (send self :intercept)
183 (format t "Constant ~10f ~A~%"
184 (car coefs) (list (car se-s)))
185 (setf coefs (cdr coefs))
186 (setf se-s (cdr se-s)))
187 (dotimes (i (array-dimension x 1))
188 (cond
189 ((member i (send self :basis))
190 (format t "~22a ~10f ~A~%"
191 (select p-names i) (car coefs) (list (car se-s)))
192 (setf coefs (cdr coefs) se-s (cdr se-s)))
193 (t (format t "~22a aliased~%" (select p-names i)))))
194 (format t "~%")
195 (format t "R Squared: ~10f~%" (send self :r-squared))
196 (format t "Sigma hat: ~10f~%" (send self :sigma-hat))
197 (format t "Number of cases: ~10d~%" (send self :num-cases))
198 (if (/= (send self :num-cases) (send self :num-included))
199 (format t "Number of cases used: ~10d~%" (send self :num-included)))
200 (format t "Degrees of freedom: ~10d~%" (send self :df))
201 (format t "~%")))
203 ;;; Slot accessors and mutators
205 (defmeth regression-model-proto :doc (&optional new-doc append)
206 "Message args: (&optional new-doc)
208 Returns the DOC-STRING as supplied to m.
209 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
210 NEW-DOC. In this setting, when APPEND is T, append NEW-DOC to DOC
211 rather than doing replacement."
212 (send self :nop)
213 (when (and new-doc (stringp new-doc))
214 (setf (slot-value 'doc)
215 (if append
216 (concatenate 'string
217 (slot-value 'doc)
218 new-doc)
219 new-doc)))
220 (slot-value 'doc))
223 (defmeth regression-model-proto :x (&optional new-x)
224 "Message args: (&optional new-x)
226 With no argument returns the x matrix as supplied to m. With an
227 argument, NEW-X sets the x matrix to NEW-X and recomputes the
228 estimates."
229 (when (and new-x (typep new-x 'matrix-like))
230 (setf (slot-value 'x) new-x)
231 (send self :needs-computing t))
232 (slot-value 'x))
234 (defmeth regression-model-proto :y (&optional new-y)
235 "Message args: (&optional new-y)
237 With no argument returns the y sequence as supplied to m. With an
238 argument, NEW-Y sets the y sequence to NEW-Y and recomputes the
239 estimates."
240 (when (and new-y
241 (or (typep new-y vector-like)
242 (typep new-y 'sequence)))
243 (setf (slot-value 'y) new-y)
244 (send self :needs-computing t))
245 (slot-value 'y))
247 (defmeth regression-model-proto :intercept (&optional (val nil set))
248 "Message args: (&optional new-intercept)
250 With no argument returns T if the model includes an intercept term,
251 nil if not. With an argument NEW-INTERCEPT the model is changed to
252 include or exclude an intercept, according to the value of
253 NEW-INTERCEPT."
254 (when set
255 (setf (slot-value 'intercept) val)
256 (send self :needs-computing t))
257 (slot-value 'intercept))
259 (defmeth regression-model-proto :weights (&optional (new-w nil set))
260 "Message args: (&optional new-w)
262 With no argument returns the weight sequence as supplied to m; NIL
263 means an unweighted model. NEW-W sets the weights sequence to NEW-W
264 and recomputes the estimates."
265 (when (and set
266 (or (typep new-y vector-like)
267 (typep new-y 'sequence)))
268 (setf (slot-value 'weights) new-w)
269 (send self :needs-computing t))
270 (slot-value 'weights))
272 (defmeth regression-model-proto :total-sum-of-squares ()
273 "Message args: ()
275 Returns the total sum of squares around the mean."
276 (if (send self :needs-computing) (send self :compute))
277 (slot-value 'total-sum-of-squares))
279 (defmeth regression-model-proto :residual-sum-of-squares ()
280 "Message args: ()
282 Returns the residual sum of squares for the model."
283 (if (send self :needs-computing) (send self :compute))
284 (slot-value 'residual-sum-of-squares))
286 (defmeth regression-model-proto :basis ()
287 "Message args: ()
289 Returns the indices of the variables used in fitting the model, in a
290 sequence. Recompute before this, if needed."
291 (if (send self :needs-computing)
292 (send self :compute))
293 ;; This should be silly -- basis MUST be a vector in the new regime.
294 (if (typep (slot-value 'basis) 'sequence)
295 (slot-value 'basis)
296 (list (slot-value 'basis))))
299 (defmeth regression-model-proto :sweep-matrix ()
300 "Message args: ()
302 Returns the swept sweep matrix. For internal use"
303 (if (send self :needs-computing)
304 (send self :compute))
305 (slot-value 'sweep-matrix))
307 (defmeth regression-model-proto :included (&optional new-included)
308 "Message args: (&optional new-included)
310 With no argument, NIL means a case is not used in calculating
311 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
312 of length of y of nil and t to select cases. Estimates are
313 recomputed."
314 (when (and new-included
315 (= (nelts new-included) (send self :num-cases)))
316 (setf (slot-value 'included) (copy-seq new-included))
317 (send self :needs-computing t))
318 (if (slot-value 'included)
319 (slot-value 'included)
320 (repeat t (send self :num-cases))))
322 (defmeth regression-model-proto :predictor-names (&optional (names nil set))
323 "Message args: (&optional (names nil set))
325 With no argument returns the predictor names. NAMES sets the names."
326 (if set (setf (slot-value 'predictor-names) (mapcar #'string names)))
327 (let ((p (matrix-dimension (send self :x) 1))
328 (p-names (slot-value 'predictor-names)))
329 (if (not (and p-names (= (length p-names) p)))
330 (setf (slot-value 'predictor-names)
331 (mapcar #'(lambda (a) (format nil "Variable ~a" a))
332 (iseq 0 (- p 1))))))
333 (slot-value 'predictor-names))
335 (defmeth regression-model-proto :response-name (&optional (name "Y" set))
336 "Message args: (&optional name)
338 With no argument returns the response name. NAME sets the name."
339 (send self :nop)
340 (if set (setf (slot-value 'response-name) (if name (string name) "Y")))
341 (slot-value 'response-name))
343 (defmeth regression-model-proto :case-labels (&optional (labels nil set))
344 "Message args: (&optional labels)
345 With no argument returns the case-labels. LABELS sets the labels."
346 (if set (setf (slot-value 'case-labels)
347 (if labels
348 (mapcar #'string labels)
349 (mapcar #'(lambda (x) (format nil "~d" x))
350 (iseq 0 (- (send self :num-cases) 1))))))
351 (slot-value 'case-labels))
354 ;;; Other Methods
355 ;;; None of these methods access any slots directly.
358 (defmeth regression-model-proto :num-cases ()
359 "Message args: ()
360 Returns the number of cases in the model."
361 (nelts (send self :y)))
363 (defmeth regression-model-proto :num-included ()
364 "Message args: ()
365 Returns the number of cases used in the computations."
366 (sum (if-else (send self :included) 1 0)))
368 (defmeth regression-model-proto :num-coefs ()
369 "Message args: ()
370 Returns the number of coefficients in the fit model (including the
371 intercept if the model includes one)."
372 (if (send self :intercept)
373 (+ 1 (nelts (send self :basis)))
374 (nelts (send self :basis))))
376 (defmeth regression-model-proto :df ()
377 "Message args: ()
378 Returns the number of degrees of freedom in the model."
379 (- (send self :num-included) (send self :num-coefs)))
381 (defmeth regression-model-proto :x-matrix ()
382 "Message args: ()
383 Returns the X matrix for the model, including a column of 1's, if
384 appropriate. Columns of X matrix correspond to entries in basis."
385 (let ((m (select (send self :x)
386 (iseq 0 (- (send self :num-cases) 1))
387 (send self :basis))))
388 (if (send self :intercept)
389 (bind2 (repeat 1 (send self :num-cases)) m)
390 m)))
392 (defmeth regression-model-proto :leverages ()
393 "Message args: ()
394 Returns the diagonal elements of the hat matrix."
395 (let* ((weights (send self :weights))
396 (x (send self :x-matrix))
397 (raw-levs
398 (matmult (* (matmult x (send self :xtxinv)) x)
399 (repeat 1 (send self :num-coefs)))))
400 (if weights (* weights raw-levs) raw-levs)))
402 (defmeth regression-model-proto :fit-values ()
403 "Message args: ()
404 Returns the fitted values for the model."
405 (matmult (send self :x-matrix) (send self :coef-estimates)))
407 (defmeth regression-model-proto :raw-residuals ()
408 "Message args: ()
409 Returns the raw residuals for a model."
410 (- (send self :y) (send self :fit-values)))
412 (defmeth regression-model-proto :residuals ()
413 "Message args: ()
414 Returns the raw residuals for a model without weights. If the model
415 includes weights the raw residuals times the square roots of the weights
416 are returned."
417 (let ((raw-residuals (send self :raw-residuals))
418 (weights (send self :weights)))
419 (if weights (* (sqrt weights) raw-residuals) raw-residuals)))
421 (defmeth regression-model-proto :sum-of-squares ()
422 "Message args: ()
423 Returns the error sum of squares for the model."
424 (send self :residual-sum-of-squares))
426 (defmeth regression-model-proto :sigma-hat ()
427 "Message args: ()
428 Returns the estimated standard deviation of the deviations about the
429 regression line."
430 (let ((ss (send self :sum-of-squares))
431 (df (send self :df)))
432 (if (/= df 0) (sqrt (/ ss df)))))
434 ;; for models without an intercept the 'usual' formula for R^2 can give
435 ;; negative results; hence the max.
436 (defmeth regression-model-proto :r-squared ()
437 "Message args: ()
438 Returns the sample squared multiple correlation coefficient, R squared, for
439 the regression."
440 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
443 (defmeth regression-model-proto :coef-estimates ()
444 "Message args: ()
446 Returns the OLS (ordinary least squares) estimates of the regression
447 coefficients. Entries beyond the intercept correspond to entries in
448 basis."
449 (let ((n (array-dimension (send self :x) 1))
450 (indices (flatten-list
451 (if (send self :intercept)
452 (cons 0 (+ 1 (send self :basis)))
453 (list (+ 1 (send self :basis))))))
454 (m (send self :sweep-matrix)))
455 (format t "~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
456 m n indices (send self :basis))
457 (coerce (compound-data-seq (select m (+ 1 n) indices)) 'list))) ;; ERROR
459 (defmeth regression-model-proto :xtxinv ()
460 "Message args: ()
461 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
462 (let ((indices (if (send self :intercept)
463 (cons 0 (1+ (send self :basis)))
464 (1+ (send self :basis)))))
465 (select (send self :sweep-matrix) indices indices)))
467 (defmeth regression-model-proto :coef-standard-errors ()
468 "Message args: ()
469 Returns estimated standard errors of coefficients. Entries beyond the
470 intercept correspond to entries in basis."
471 (let ((s (send self :sigma-hat)))
472 (if s (* (send self :sigma-hat) (sqrt (diagonal (send self :xtxinv)))))))
474 (defmeth regression-model-proto :studentized-residuals ()
475 "Message args: ()
476 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
477 (let ((res (send self :residuals))
478 (lev (send self :leverages))
479 (sig (send self :sigma-hat))
480 (inc (send self :included)))
481 (if-else inc
482 (/ res (* sig (sqrt (pmax .00001 (- 1 lev)))))
483 (/ res (* sig (sqrt (+ 1 lev)))))))
485 (defmeth regression-model-proto :externally-studentized-residuals ()
486 "Message args: ()
487 Computes the externally studentized residuals."
488 (let* ((res (send self :studentized-residuals))
489 (df (send self :df)))
490 (if-else (send self :included)
491 (* res (sqrt (/ (- df 1) (- df (^ res 2)))))
492 res)))
494 (defmeth regression-model-proto :cooks-distances ()
495 "Message args: ()
496 Computes Cook's distances."
497 (let ((lev (send self :leverages))
498 (res (/ (^ (send self :studentized-residuals) 2)
499 (send self :num-coefs))))
500 (if-else (send self :included) (* res (/ lev (- 1 lev) )) (* res lev))))
503 (defun plot-points (x y &rest args)
504 "need to fix."
505 (declare (ignore x y args))
506 (error "Graphics not implemented yet."))
508 ;; Can not plot points yet!!
509 (defmeth regression-model-proto :plot-residuals (&optional x-values)
510 "Message args: (&optional x-values)
511 Opens a window with a plot of the residuals. If X-VALUES are not supplied
512 the fitted values are used. The plot can be linked to other plots with the
513 link-views function. Returns a plot object."
514 (plot-points (if x-values x-values (send self :fit-values))
515 (send self :residuals)
516 :title "Residual Plot"
517 :point-labels (send self :case-labels)))
519 (defmeth regression-model-proto :plot-bayes-residuals
520 (&optional x-values)
521 "Message args: (&optional x-values)
523 Opens a window with a plot of the standardized residuals and two
524 standard error bars for the posterior distribution of the actual
525 deviations from the line. See Chaloner and Brant. If X-VALUES are not
526 supplied the fitted values are used. The plot can be linked to other
527 plots with the link-views function. Returns a plot object."
529 (let* ((r (/ (send self :residuals)
530 (send self :sigma-hat)))
531 (d (* 2 (sqrt (send self :leverages))))
532 (low (- r d))
533 (high (+ r d))
534 (x-values (if x-values x-values (send self :fit-values)))
535 (p (plot-points x-values r
536 :title "Bayes Residual Plot"
537 :point-labels (send self :case-labels))))
538 (map 'list #'(lambda (a b c d) (send p :plotline a b c d nil))
539 x-values low x-values high)
540 (send p :adjust-to-data)