docs on approach for modeling issues.
[CommonLispStat.git] / src / stat-models / regression.lisp
blob2e3ad0a23e5ba7c3d2d37a5fd76474f739fd68f6
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.
123 ;; There are conflicting theories for how to structure the
124 ;; specification of mathematical models, along with the statistical
125 ;; inference, along with the data which is instantiating the model.
127 ;; i.e.: mathematical model for the relationships between components,
128 ;; between a component and a summarizing parameter, and between
129 ;; parameters.
131 ;; statistical inference describes the general approach for
132 ;; aggregating into a decision and has impliciations for the scale up
133 ;; from the model on a single instance to the generalization.
135 ;; The data represents the particular substantive context that is
136 ;; driving the model/inference combination, and about which we hope to
137 ;; generate knowledge.
139 ;; numerical analysis selects appropriate algorithms/implementations
140 ;; for combining the above 3.
142 ;; the end result is input on the decision being made (which could be
143 ;; specific (decision analysis/testing), risk-analysis (interval
144 ;; estimation) , most likely/appropriate selection (point estimation)
148 (defclass model ()
149 ((type structure)))
151 (defgeneric regression ;; assumes x/y from lisp-matrix -- start of a set of generics.
152 (model dataset)
153 "Args: (x y &key (intercept T) (print T) (weights nil)
154 included predictor-names response-name case-labels)
155 X - list of independent variables or X matrix
156 Y - dependent variable.
157 INTERCEPT - T to include (default), NIL for no intercept
158 PRINT - if not NIL print summary information
159 WEIGHTS - if supplied should be the same length as Y; error
160 variances are
161 assumed to be inversely proportional to WEIGHTS
162 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
163 - sequences of strings or symbols.
164 INCLUDED - if supplied should be the same length as Y, with
165 elements nil to skip a in computing estimates (but not
166 in residual analysis).
167 Returns a regression model object. To examine the model further assign the
168 result to a variable and send it messages.
169 Example (data are in file absorbtion.lsp in the sample data directory):
170 (def m (regression-model (list iron aluminum) absorbtion))
171 (send m :help) (send m :plot-residuals)"
172 (let ((m (send regression-model-proto :new)))
173 (format t "~%")
174 (send m :doc doc)
175 (send m :x x)
176 (send m :y y)
177 (send m :intercept intercept)
178 (send m :weights weights)
179 (send m :included included)
180 (send m :predictor-names predictor-names)
181 (send m :response-name response-name)
182 (send m :case-labels case-labels)
183 (if debug
184 (progn
185 (format t "~%")
186 (format t "~S~%" (send m :doc))
187 (format t "X: ~S~%" (send m :x))
188 (format t "Y: ~S~%" (send m :y))))
189 (if print (send m :display))
194 (defmeth regression-model-proto :isnew ()
195 (send self :needs-computing t))
197 (defmeth regression-model-proto :save ()
198 "Message args: ()
199 Returns an expression that will reconstruct the regression model."
200 `(regression-model ',(send self :x)
201 ',(send self :y)
202 :intercept ',(send self :intercept)
203 :weights ',(send self :weights)
204 :included ',(send self :included)
205 :predictor-names ',(send self :predictor-names)
206 :response-name ',(send self :response-name)
207 :case-labels ',(send self :case-labels)))
209 ;;; Computing and Display Methods
211 (defmeth regression-model-proto :compute ()
212 "Message args: ()
213 Recomputes the estimates. For internal use by other messages"
214 (let* ((included (if-else (send self :included) 1 0))
215 (x (send self :x))
216 (y (send self :y))
217 (intercept (send self :intercept))
218 (weights (send self :weights))
219 (w (if weights (* included weights) included))
220 (m (make-sweep-matrix x y w)) ;;; ERROR HERE
221 (n (matrix-dimension x 1))
222 (p (- (matrix-dimension m 0) 1))
223 (tss (mref m p p))
224 (tol (* 0.001
225 (reduce #'* (mapcar #'standard-deviation (list-of-columns x)))))
226 (sweep-result
227 (if intercept
228 (sweep-operator m (iseq 1 n) tol)
229 (sweep-operator m (iseq 0 n) (cons 0.0 tol)))))
230 (format t
231 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
232 sweep-result x y m tss)
233 (setf (slot-value 'sweep-matrix) (first sweep-result))
234 (setf (slot-value 'total-sum-of-squares) tss)
235 (setf (slot-value 'residual-sum-of-squares)
236 (mref (first sweep-result) p p))
237 ;; SOMETHING WRONG HERE! FIX-ME
238 (setf (slot-value 'basis)
239 (let ((b (remove 0 (second sweep-result))))
240 (if b (- (reduce #'- (reverse b)) 1)
241 (error "no columns could be swept"))))))
243 (defmeth regression-model-proto :needs-computing (&optional set)
244 "Message args: ( &optional set )
246 If value given, sets the flag for whether (re)computation is needed to
247 update the model fits."
248 (send self :nop)
249 (if set (setf (slot-value 'sweep-matrix) nil))
250 (null (slot-value 'sweep-matrix)))
252 (defmeth regression-model-proto :display ()
253 "Message args: ()
255 Prints the least squares regression summary. Variables not used in the fit
256 are marked as aliased."
257 (let ((coefs (coerce (send self :coef-estimates) 'list))
258 (se-s (send self :coef-standard-errors))
259 (x (send self :x))
260 (p-names (send self :predictor-names)))
261 (if (send self :weights)
262 (format t "~%Weighted Least Squares Estimates:~2%")
263 (format t "~%Least Squares Estimates:~2%"))
264 (when (send self :intercept)
265 (format t "Constant ~10f ~A~%"
266 (car coefs) (list (car se-s)))
267 (setf coefs (cdr coefs))
268 (setf se-s (cdr se-s)))
269 (dotimes (i (array-dimension x 1))
270 (cond
271 ((member i (send self :basis))
272 (format t "~22a ~10f ~A~%"
273 (select p-names i) (car coefs) (list (car se-s)))
274 (setf coefs (cdr coefs) se-s (cdr se-s)))
275 (t (format t "~22a aliased~%" (select p-names i)))))
276 (format t "~%")
277 (format t "R Squared: ~10f~%" (send self :r-squared))
278 (format t "Sigma hat: ~10f~%" (send self :sigma-hat))
279 (format t "Number of cases: ~10d~%" (send self :num-cases))
280 (if (/= (send self :num-cases) (send self :num-included))
281 (format t "Number of cases used: ~10d~%" (send self :num-included)))
282 (format t "Degrees of freedom: ~10d~%" (send self :df))
283 (format t "~%")))
285 ;;; Slot accessors and mutators
287 (defmeth regression-model-proto :doc (&optional new-doc append)
288 "Message args: (&optional new-doc)
290 Returns the DOC-STRING as supplied to m.
291 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
292 NEW-DOC. In this setting, when APPEND is T, append NEW-DOC to DOC
293 rather than doing replacement."
294 (send self :nop)
295 (when (and new-doc (stringp new-doc))
296 (setf (slot-value 'doc)
297 (if append
298 (concatenate 'string
299 (slot-value 'doc)
300 new-doc)
301 new-doc)))
302 (slot-value 'doc))
305 (defmeth regression-model-proto :x (&optional new-x)
306 "Message args: (&optional new-x)
308 With no argument returns the x matrix-like as supplied to m. With an
309 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
310 estimates."
311 (when (and new-x (typep new-x 'matrix-like))
312 (setf (slot-value 'x) new-x)
313 (send self :needs-computing t))
314 (slot-value 'x))
316 (defmeth regression-model-proto :y (&optional new-y)
317 "Message args: (&optional new-y)
319 With no argument returns the y vector-like as supplied to m. With an
320 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
321 estimates."
322 (when (and new-y
323 (typep new-y 'vector-like))
324 (setf (slot-value 'y) new-y) ;; fixme -- pls set slot value to a vector-like!
325 (send self :needs-computing t))
326 (slot-value 'y))
328 (defmeth regression-model-proto :intercept (&optional (val nil set))
329 "Message args: (&optional new-intercept)
331 With no argument returns T if the model includes an intercept term,
332 nil if not. With an argument NEW-INTERCEPT the model is changed to
333 include or exclude an intercept, according to the value of
334 NEW-INTERCEPT."
335 (when set
336 (setf (slot-value 'intercept) val)
337 (send self :needs-computing t))
338 (slot-value 'intercept))
340 (defmeth regression-model-proto :weights (&optional (new-w nil set))
341 "Message args: (&optional new-w)
343 With no argument returns the weight vector-like as supplied to m; NIL
344 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
345 and recomputes the estimates."
346 (when (and set
347 (typep new-w 'vector-like))
348 (setf (slot-value 'weights) new-w)
349 (send self :needs-computing t))
350 (slot-value 'weights))
352 (defmeth regression-model-proto :total-sum-of-squares ()
353 "Message args: ()
355 Returns the total sum of squares around the mean.
356 This is recomputed if an update is needed."
357 (if (send self :needs-computing)
358 (send self :compute))
359 (slot-value 'total-sum-of-squares))
361 (defmeth regression-model-proto :residual-sum-of-squares ()
362 "Message args: ()
364 Returns the residual sum of squares for the model.
365 This is recomputed if an update is needed."
366 (if (send self :needs-computing)
367 (send self :compute))
368 (slot-value 'residual-sum-of-squares))
370 (defmeth regression-model-proto :basis ()
371 "Message args: ()
373 Returns the indices of the variables used in fitting the model, in a
374 sequence.
375 This is recomputed if an update is needed."
376 (if (send self :needs-computing)
377 (send self :compute))
378 (slot-value 'basis))
381 (defmeth regression-model-proto :sweep-matrix ()
382 "Message args: ()
384 Returns the swept sweep matrix. For internal use"
385 (if (send self :needs-computing)
386 (send self :compute))
387 (slot-value 'sweep-matrix))
389 (defmeth regression-model-proto :included (&optional new-included)
390 "Message args: (&optional new-included)
392 With no argument, NIL means a case is not used in calculating
393 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
394 of length of y of nil and t to select cases. Estimates are
395 recomputed."
396 (when (and new-included
397 (= (nelts new-included) (send self :num-cases)))
398 (setf (slot-value 'included) (copy-seq new-included))
399 (send self :needs-computing t))
400 (if (slot-value 'included)
401 (slot-value 'included)
402 (repeat t (send self :num-cases))))
404 (defmeth regression-model-proto :predictor-names (&optional (names nil set))
405 "Message args: (&optional (names nil set))
407 With no argument returns the predictor names. NAMES sets the names."
408 (if set (setf (slot-value 'predictor-names) (mapcar #'string names)))
409 (let ((p (matrix-dimension (send self :x) 1))
410 (p-names (slot-value 'predictor-names)))
411 (if (not (and p-names (= (length p-names) p)))
412 (setf (slot-value 'predictor-names)
413 (mapcar #'(lambda (a) (format nil "Variable ~a" a))
414 (iseq 0 (- p 1))))))
415 (slot-value 'predictor-names))
417 (defmeth regression-model-proto :response-name (&optional (name "Y" set))
418 "Message args: (&optional name)
420 With no argument returns the response name. NAME sets the name."
421 (send self :nop)
422 (if set (setf (slot-value 'response-name) (if name (string name) "Y")))
423 (slot-value 'response-name))
425 (defmeth regression-model-proto :case-labels (&optional (labels nil set))
426 "Message args: (&optional labels)
427 With no argument returns the case-labels. LABELS sets the labels."
428 (if set (setf (slot-value 'case-labels)
429 (if labels
430 (mapcar #'string labels)
431 (mapcar #'(lambda (x) (format nil "~d" x))
432 (iseq 0 (- (send self :num-cases) 1))))))
433 (slot-value 'case-labels))
436 ;;; Other Methods
437 ;;; None of these methods access any slots directly.
440 (defmeth regression-model-proto :num-cases ()
441 "Message args: ()
442 Returns the number of cases in the model."
443 (nelts (send self :y)))
445 (defmeth regression-model-proto :num-included ()
446 "Message args: ()
447 Returns the number of cases used in the computations."
448 (sum (if-else (send self :included) 1 0)))
450 (defmeth regression-model-proto :num-coefs ()
451 "Message args: ()
452 Returns the number of coefficients in the fit model (including the
453 intercept if the model includes one)."
454 (if (send self :intercept)
455 (+ 1 (nelts (send self :basis)))
456 (nelts (send self :basis))))
458 (defmeth regression-model-proto :df ()
459 "Message args: ()
460 Returns the number of degrees of freedom in the model."
461 (- (send self :num-included) (send self :num-coefs)))
463 (defmeth regression-model-proto :x-matrix ()
464 "Message args: ()
465 Returns the X matrix for the model, including a column of 1's, if
466 appropriate. Columns of X matrix correspond to entries in basis."
467 (let ((m (select (send self :x)
468 (iseq 0 (- (send self :num-cases) 1))
469 (send self :basis))))
470 (if (send self :intercept)
471 (bind2 (repeat 1 (send self :num-cases)) m)
472 m)))
474 (defmeth regression-model-proto :leverages ()
475 "Message args: ()
476 Returns the diagonal elements of the hat matrix."
477 (let* ((weights (send self :weights))
478 (x (send self :x-matrix))
479 (raw-levs
480 (m* (* (m* x (send self :xtxinv)) x)
481 (repeat 1 (send self :num-coefs)))))
482 (if weights (* weights raw-levs) raw-levs)))
484 (defmeth regression-model-proto :fit-values ()
485 "Message args: ()
486 Returns the fitted values for the model."
487 (m* (send self :x-matrix) (send self :coef-estimates)))
489 (defmeth regression-model-proto :raw-residuals ()
490 "Message args: ()
491 Returns the raw residuals for a model."
492 (- (send self :y) (send self :fit-values)))
494 (defmeth regression-model-proto :residuals ()
495 "Message args: ()
496 Returns the raw residuals for a model without weights. If the model
497 includes weights the raw residuals times the square roots of the weights
498 are returned."
499 (let ((raw-residuals (send self :raw-residuals))
500 (weights (send self :weights)))
501 (if weights (* (sqrt weights) raw-residuals) raw-residuals)))
503 (defmeth regression-model-proto :sum-of-squares ()
504 "Message args: ()
505 Returns the error sum of squares for the model."
506 (send self :residual-sum-of-squares))
508 (defmeth regression-model-proto :sigma-hat ()
509 "Message args: ()
510 Returns the estimated standard deviation of the deviations about the
511 regression line."
512 (let ((ss (send self :sum-of-squares))
513 (df (send self :df)))
514 (if (/= df 0) (sqrt (/ ss df)))))
516 ;; for models without an intercept the 'usual' formula for R^2 can give
517 ;; negative results; hence the max.
518 (defmeth regression-model-proto :r-squared ()
519 "Message args: ()
520 Returns the sample squared multiple correlation coefficient, R squared, for
521 the regression."
522 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
525 (defmeth regression-model-proto :coef-estimates ()
526 "Message args: ()
528 Returns the OLS (ordinary least squares) estimates of the regression
529 coefficients. Entries beyond the intercept correspond to entries in
530 basis."
531 (let ((n (array-dimension (send self :x) 1))
532 (indices (flatten-list
533 (if (send self :intercept)
534 (cons 0 (+ 1 (send self :basis)))
535 (list (+ 1 (send self :basis))))))
536 (m (send self :sweep-matrix)))
537 (format t "~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
538 m n indices (send self :basis))
539 (coerce (compound-data-seq (select m (+ 1 n) indices)) 'list))) ;; ERROR
541 (defmeth regression-model-proto :xtxinv ()
542 "Message args: ()
543 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
544 (let ((indices (if (send self :intercept)
545 (cons 0 (1+ (send self :basis)))
546 (1+ (send self :basis)))))
547 (select (send self :sweep-matrix) indices indices)))
549 (defmeth regression-model-proto :coef-standard-errors ()
550 "Message args: ()
551 Returns estimated standard errors of coefficients. Entries beyond the
552 intercept correspond to entries in basis."
553 (let ((s (send self :sigma-hat)))
554 (if s (* (send self :sigma-hat) (sqrt (diagonalf (send self :xtxinv)))))))
556 (defmeth regression-model-proto :studentized-residuals ()
557 "Message args: ()
558 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
559 (let ((res (send self :residuals))
560 (lev (send self :leverages))
561 (sig (send self :sigma-hat))
562 (inc (send self :included)))
563 (if-else inc
564 (/ res (* sig (sqrt (pmax .00001 (- 1 lev)))))
565 (/ res (* sig (sqrt (+ 1 lev)))))))
567 (defmeth regression-model-proto :externally-studentized-residuals ()
568 "Message args: ()
569 Computes the externally studentized residuals."
570 (let* ((res (send self :studentized-residuals))
571 (df (send self :df)))
572 (if-else (send self :included)
573 (* res (sqrt (/ (- df 1) (- df (^ res 2)))))
574 res)))
576 (defmeth regression-model-proto :cooks-distances ()
577 "Message args: ()
578 Computes Cook's distances."
579 (let ((lev (send self :leverages))
580 (res (/ (^ (send self :studentized-residuals) 2)
581 (send self :num-coefs))))
582 (if-else (send self :included) (* res (/ lev (- 1 lev) )) (* res lev))))
585 (defun plot-points (x y &rest args)
586 "need to fix."
587 (declare (ignore x y args))
588 (error "Graphics not implemented yet."))
590 ;; Can not plot points yet!!
591 (defmeth regression-model-proto :plot-residuals (&optional x-values)
592 "Message args: (&optional x-values)
593 Opens a window with a plot of the residuals. If X-VALUES are not supplied
594 the fitted values are used. The plot can be linked to other plots with the
595 link-views function. Returns a plot object."
596 (plot-points (if x-values x-values (send self :fit-values))
597 (send self :residuals)
598 :title "Residual Plot"
599 :point-labels (send self :case-labels)))
601 (defmeth regression-model-proto :plot-bayes-residuals
602 (&optional x-values)
603 "Message args: (&optional x-values)
605 Opens a window with a plot of the standardized residuals and two
606 standard error bars for the posterior distribution of the actual
607 deviations from the line. See Chaloner and Brant. If X-VALUES are not
608 supplied the fitted values are used. The plot can be linked to other
609 plots with the link-views function. Returns a plot object."
611 (let* ((r (/ (send self :residuals)
612 (send self :sigma-hat)))
613 (d (* 2 (sqrt (send self :leverages))))
614 (low (- r d))
615 (high (+ r d))
616 (x-values (if x-values x-values (send self :fit-values)))
617 (p (plot-points x-values r
618 :title "Bayes Residual Plot"
619 :point-labels (send self :case-labels))))
620 (map 'list #'(lambda (a b c d) (send p :plotline a b c d nil))
621 x-values low x-values high)
622 (send p :adjust-to-data)