ignoring ext links
[CommonLispStat.git] / regression-matlisp.lsp
blob512fb2b3459466f0cb55f8e5e313014f664dced0
1 ;;; -*- mode: lisp -*-
2 ;;;
3 ;;; Copyright (c) 2005--2007, 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 ;;;
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 ;;;
16 ;;; Incorporates modifications suggested by Sandy Weisberg.
17 ;;;
18 ;;; Modified to use MATLISP as the matrix package, rather than
19 ;;; homebrewed linear algebra.
21 (in-package :cl-user)
23 (defpackage :lisp-stat-regression-linear
24 (:use :common-lisp
25 :lisp-stat-object-system
26 :matlisp
27 :lisp-stat-basics
28 :lisp-stat-compound-data
29 :lisp-stat-math
30 :lisp-stat-descriptive-statistics)
31 (:shadowing-import-from :lisp-stat-object-system
32 slot-value call-method call-next-method)
33 (:shadowing-import-from :matlisp
34 real)
35 (:shadowing-import-from :lisp-stat-math
36 expt + - * / ** mod rem abs 1+ 1- log exp sqrt sin cos tan
37 asin acos atan sinh cosh tanh asinh acosh atanh float random
38 truncate floor ceiling round minusp zerop plusp evenp oddp
39 < <= = /= >= > ;; complex
40 conjugate realpart imagpart phase
41 min max logand logior logxor lognot ffloor fceiling
42 ftruncate fround signum cis)
43 (:export regression-model regression-model-proto x y intercept
44 sweep-matrix
45 basis weights included total-sum-of-squares
46 residual-sum-of-squares
47 predictor-names response-name case-labels))
49 (in-package :lisp-stat-regression-linear)
51 ;;; Regresion Model Prototype
54 ;; The general strategy behind the fitting of models using prototypes
55 ;; is that we need to think about want the actual fits are, and then
56 ;; the fits can be used to recompute as components are changes. One
57 ;; catch here is that we'd like some notion of trace-ability, in
58 ;; particular, there is not necessarily a fixed way to take care of the
59 ;; audit trail. save-nd-die might be a means of recording the final
60 ;; approach, but we are challenged by the problem of using advice and
61 ;; other such features to capture stages and steps that are considered
62 ;; along the goals of estimating a model.
64 (defvar regression-model-proto nil
65 "Prototype for all regression model instances.")
66 (defproto regression-model-proto
67 '(x y intercept sweep-matrix basis weights
68 included
69 total-sum-of-squares
70 residual-sum-of-squares
71 predictor-names
72 response-name
73 case-labels
74 doc)
76 *object*
77 "Normal Linear Regression Model")
79 (defun regression-model (x y &key
80 (intercept T)
81 (print T)
82 (weights nil)
83 (included (repeat t (length y)))
84 predictor-names
85 response-name
86 case-labels
87 (doc "Undocumented Regression Model Instance")
88 (debug T))
89 "Args: (x y &key (intercept T) (print T) (weights nil)
90 included predictor-names response-name case-labels)
91 X - list of independent variables or X matrix
92 Y - dependent variable.
93 INTERCEPT - T to include (default), NIL for no intercept
94 PRINT - if not NIL print summary information
95 WEIGHTS - if supplied should be the same length as Y; error
96 variances are
97 assumed to be inversely proportional to WEIGHTS
98 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
99 - sequences of strings or symbols.
100 INCLUDED - if supplied should be the same length as Y, with
101 elements nil to skip a in computing estimates (but not
102 in residual analysis).
103 Returns a regression model object. To examine the model further assign the
104 result to a variable and send it messages.
105 Example (data are in file absorbtion.lsp in the sample data directory):
106 (def m (regression-model (list iron aluminum) absorbtion))
107 (send m :help) (send m :plot-residuals)"
108 (let ((x (cond
109 ((typep x 'real-matrix) x) ;; matrix, or ...
110 (t (error "Regression: X is not a real matrix")))) ;; defaulting...
111 (m (send regression-model-proto :new)))
112 (format t "~%")
113 (send m :doc doc)
114 (send m :x x)
115 (send m :y y)
116 (send m :intercept intercept)
117 (send m :weights weights)
118 (send m :included included)
119 (send m :predictor-names predictor-names)
120 (send m :response-name response-name)
121 (send m :case-labels case-labels)
122 (if debug
123 (progn
124 (format t "~%")
125 (format t "~S~%" (send m :doc))
126 (format t "X: ~S~%" (send m :x))
127 (format t "Y: ~S~%" (send m :y))))
128 (if print (send m :display))
131 (defmeth regression-model-proto :isnew ()
132 (send self :needs-computing t))
134 (defmeth regression-model-proto :save ()
135 "Message args: ()
136 Returns an expression that will reconstruct the regression model."
137 `(regression-model ',(send self :x)
138 ',(send self :y)
139 :intercept ',(send self :intercept)
140 :weights ',(send self :weights)
141 :included ',(send self :included)
142 :predictor-names ',(send self :predictor-names)
143 :response-name ',(send self :response-name)
144 :case-labels ',(send self :case-labels)))
146 ;;; Computing and Display Methods
148 (defmeth regression-model-proto :compute ()
149 "Message args: ()
150 Recomputes the estimates. For internal use by other messages"
151 (let* ((included (if-else (send self :included) 1 0))
152 (x (send self :x))
153 (y (send self :y))
154 (intercept (send self :intercept))
155 (weights (send self :weights))
156 (w (if weights (* included weights) included))
157 (m (make-sweep-matrix x y w)) ;;; ERROR HERE
158 (n (array-dimension x 1))
159 (p (- (array-dimension m 0) 1))
160 (tss (aref m p p))
161 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation (column-list x)))))
162 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
163 (sweep-result
164 (if intercept
165 (sweep-operator m (iseq 1 n) tol)
166 (sweep-operator m (iseq 0 n) (cons 0.0 tol)))))
167 (format t
168 "~%REMOVEME: regr-mdl-prto :compute =~A~%~A~%~A~%~A~%~A~%"
169 sweep-result x y m tss)
170 (setf (slot-value 'sweep-matrix) (first sweep-result))
171 (setf (slot-value 'total-sum-of-squares) tss)
172 (setf (slot-value 'residual-sum-of-squares)
173 (aref (first sweep-result) p p))
174 (setf (slot-value 'basis)
175 (let ((b (remove 0 (second sweep-result))))
176 (if b (- (reduce #'- (reverse b)) 1)
177 (error "no columns could be swept"))))))
179 (defmeth regression-model-proto :needs-computing (&optional set)
180 "Message args: ( &optional set )
182 If value given, sets the flag for whether (re)computation is needed to
183 update the model fits."
184 (send self :nop)
185 (if set (setf (slot-value 'sweep-matrix) nil))
186 (null (slot-value 'sweep-matrix)))
188 (defmeth regression-model-proto :display ()
189 "Message args: ()
191 Prints the least squares regression summary. Variables not used in the fit
192 are marked as aliased."
193 (let ((coefs (coerce (send self :coef-estimates) 'list))
194 (se-s (send self :coef-standard-errors))
195 (x (send self :x))
196 (p-names (send self :predictor-names)))
197 (if (send self :weights)
198 (format t "~%Weighted Least Squares Estimates:~2%")
199 (format t "~%Least Squares Estimates:~2%"))
200 (when (send self :intercept)
201 (format t "Constant ~10f ~A~%"
202 (car coefs) (list (car se-s)))
203 (setf coefs (cdr coefs))
204 (setf se-s (cdr se-s)))
205 (dotimes (i (array-dimension x 1))
206 (cond
207 ((member i (send self :basis))
208 (format t "~22a ~10f ~A~%"
209 (select p-names i) (car coefs) (list (car se-s)))
210 (setf coefs (cdr coefs) se-s (cdr se-s)))
211 (t (format t "~22a aliased~%" (select p-names i)))))
212 (format t "~%")
213 (format t "R Squared: ~10f~%" (send self :r-squared))
214 (format t "Sigma hat: ~10f~%" (send self :sigma-hat))
215 (format t "Number of cases: ~10d~%" (send self :num-cases))
216 (if (/= (send self :num-cases) (send self :num-included))
217 (format t "Number of cases used: ~10d~%" (send self :num-included)))
218 (format t "Degrees of freedom: ~10d~%" (send self :df))
219 (format t "~%")))
221 ;;; Slot accessors and mutators
223 (defmeth regression-model-proto :doc (&optional new-doc append)
224 "Message args: (&optional new-doc)
226 Returns the DOC-STRING as supplied to m.
227 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
228 NEW-DOC. In this setting, when APPEND is T, append NEW-DOC to DOC
229 rather than doing replacement."
230 (send self :nop)
231 (when (and new-doc (stringp new-doc))
232 (setf (slot-value 'doc)
233 (if append
234 (concatenate 'string
235 (slot-value 'doc)
236 new-doc)
237 new-doc)))
238 (slot-value 'doc))
241 (defmeth regression-model-proto :x (&optional new-x)
242 "Message args: (&optional new-x)
244 With no argument returns the x matrix as supplied to m. With an
245 argument, NEW-X sets the x matrix to NEW-X and recomputes the
246 estimates."
247 (when (and new-x (matrixp new-x))
248 (setf (slot-value 'x) new-x)
249 (send self :needs-computing t))
250 (slot-value 'x))
252 (defmeth regression-model-proto :y (&optional new-y)
253 "Message args: (&optional new-y)
255 With no argument returns the y sequence as supplied to m. With an
256 argument, NEW-Y sets the y sequence to NEW-Y and recomputes the
257 estimates."
258 (when (and new-y
259 (or (matrixp new-y)
260 (typep new-y 'sequence)))
261 (let ((mat-y (coerce-seq-to-1d-col-matrix new-y)))
262 (setf (slot-value 'y) new-y)
263 (send self :needs-computing t)))
264 (slot-value 'y))
266 (defmeth regression-model-proto :intercept (&optional (val nil set))
267 "Message args: (&optional new-intercept)
269 With no argument returns T if the model includes an intercept term,
270 nil if not. With an argument NEW-INTERCEPT the model is changed to
271 include or exclude an intercept, according to the value of
272 NEW-INTERCEPT."
273 (when set
274 (setf (slot-value 'intercept) val)
275 (send self :needs-computing t))
276 (slot-value 'intercept))
278 (defmeth regression-model-proto :weights (&optional (new-w nil set))
279 "Message args: (&optional new-w)
281 With no argument returns the weight sequence as supplied to m; NIL
282 means an unweighted model. NEW-W sets the weights sequence to NEW-W
283 and recomputes the estimates."
284 (when set
285 (setf (slot-value 'weights) new-w)
286 (send self :needs-computing t))
287 (slot-value 'weights))
289 (defmeth regression-model-proto :total-sum-of-squares ()
290 "Message args: ()
292 Returns the total sum of squares around the mean."
293 (if (send self :needs-computing) (send self :compute))
294 (slot-value 'total-sum-of-squares))
296 (defmeth regression-model-proto :residual-sum-of-squares ()
297 "Message args: ()
299 Returns the residual sum of squares for the model."
300 (if (send self :needs-computing) (send self :compute))
301 (slot-value 'residual-sum-of-squares))
303 (defmeth regression-model-proto :basis ()
304 "Message args: ()
306 Returns the indices of the variables used in fitting the model, in a
307 sequence."
308 (if (send self :needs-computing)
309 (send self :compute))
310 (if (typep (slot-value 'basis) 'sequence)
311 (slot-value 'basis)
312 (list (slot-value 'basis))))
315 (defmeth regression-model-proto :sweep-matrix ()
316 "Message args: ()
318 Returns the swept sweep matrix. For internal use"
319 (if (send self :needs-computing)
320 (send self :compute))
321 (slot-value 'sweep-matrix))
323 (defmeth regression-model-proto :included (&optional new-included)
324 "Message args: (&optional new-included)
326 With no argument, NIL means a case is not used in calculating
327 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
328 of length of y of nil and t to select cases. Estimates are
329 recomputed."
330 (when (and new-included
331 (= (length new-included) (send self :num-cases)))
332 (setf (slot-value 'included) (copy-seq new-included))
333 (send self :needs-computing t))
334 (if (slot-value 'included)
335 (slot-value 'included)
336 (repeat t (send self :num-cases))))
338 (defmeth regression-model-proto :predictor-names (&optional (names nil set))
339 "Message args: (&optional (names nil set))
341 With no argument returns the predictor names. NAMES sets the names."
342 (if set (setf (slot-value 'predictor-names) (mapcar #'string names)))
343 (let ((p (array-dimension (send self :x) 1))
344 (p-names (slot-value 'predictor-names)))
345 (if (not (and p-names (= (length p-names) p)))
346 (setf (slot-value 'predictor-names)
347 (mapcar #'(lambda (a) (format nil "Variable ~a" a))
348 (iseq 0 (- p 1))))))
349 (slot-value 'predictor-names))
351 (defmeth regression-model-proto :response-name (&optional (name "Y" set))
352 "Message args: (&optional name)
354 With no argument returns the response name. NAME sets the name."
355 (send self :nop)
356 (if set (setf (slot-value 'response-name) (if name (string name) "Y")))
357 (slot-value 'response-name))
359 (defmeth regression-model-proto :case-labels (&optional (labels nil set))
360 "Message args: (&optional labels)
361 With no argument returns the case-labels. LABELS sets the labels."
362 (if set (setf (slot-value 'case-labels)
363 (if labels
364 (mapcar #'string labels)
365 (mapcar #'(lambda (x) (format nil "~d" x))
366 (iseq 0 (- (send self :num-cases) 1))))))
367 (slot-value 'case-labels))
370 ;;; Other Methods
371 ;;; None of these methods access any slots directly.
374 (defmeth regression-model-proto :num-cases ()
375 "Message args: ()
376 Returns the number of cases in the model."
377 (length (send self :y)))
379 (defmeth regression-model-proto :num-included ()
380 "Message args: ()
381 Returns the number of cases used in the computations."
382 (sum (if-else (send self :included) 1 0)))
384 (defmeth regression-model-proto :num-coefs ()
385 "Message args: ()
386 Returns the number of coefficients in the fit model (including the
387 intercept if the model includes one)."
388 (if (send self :intercept)
389 (+ 1 (length (send self :basis)))
390 (length (send self :basis))))
392 (defmeth regression-model-proto :df ()
393 "Message args: ()
394 Returns the number of degrees of freedom in the model."
395 (- (send self :num-included) (send self :num-coefs)))
397 (defmeth regression-model-proto :x-matrix ()
398 "Message args: ()
399 Returns the X matrix for the model, including a column of 1's, if
400 appropriate. Columns of X matrix correspond to entries in basis."
401 (let ((m (select (send self :x)
402 (iseq 0 (- (send self :num-cases) 1))
403 (send self :basis))))
404 (if (send self :intercept)
405 (bind-columns (repeat 1 (send self :num-cases)) m)
406 m)))
408 (defmeth regression-model-proto :leverages ()
409 "Message args: ()
410 Returns the diagonal elements of the hat matrix."
411 (let* ((weights (send self :weights))
412 (x (send self :x-matrix))
413 (raw-levs
414 (matmult (* (matmult x (send self :xtxinv)) x)
415 (repeat 1 (send self :num-coefs)))))
416 (if weights (* weights raw-levs) raw-levs)))
418 (defmeth regression-model-proto :fit-values ()
419 "Message args: ()
420 Returns the fitted values for the model."
421 (matmult (send self :x-matrix) (send self :coef-estimates)))
423 (defmeth regression-model-proto :raw-residuals ()
424 "Message args: ()
425 Returns the raw residuals for a model."
426 (- (send self :y) (send self :fit-values)))
428 (defmeth regression-model-proto :residuals ()
429 "Message args: ()
430 Returns the raw residuals for a model without weights. If the model
431 includes weights the raw residuals times the square roots of the weights
432 are returned."
433 (let ((raw-residuals (send self :raw-residuals))
434 (weights (send self :weights)))
435 (if weights (* (sqrt weights) raw-residuals) raw-residuals)))
437 (defmeth regression-model-proto :sum-of-squares ()
438 "Message args: ()
439 Returns the error sum of squares for the model."
440 (send self :residual-sum-of-squares))
442 (defmeth regression-model-proto :sigma-hat ()
443 "Message args: ()
444 Returns the estimated standard deviation of the deviations about the
445 regression line."
446 (let ((ss (send self :sum-of-squares))
447 (df (send self :df)))
448 (if (/= df 0) (sqrt (/ ss df)))))
450 ;; for models without an intercept the 'usual' formula for R^2 can give
451 ;; negative results; hence the max.
452 (defmeth regression-model-proto :r-squared ()
453 "Message args: ()
454 Returns the sample squared multiple correlation coefficient, R squared, for
455 the regression."
456 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
459 (defmeth regression-model-proto :coef-estimates ()
460 "Message args: ()
462 Returns the OLS (ordinary least squares) estimates of the regression
463 coefficients. Entries beyond the intercept correspond to entries in
464 basis."
465 (let ((n (array-dimension (send self :x) 1))
466 (indices (flatten-list
467 (if (send self :intercept)
468 (list 0 (+ 1 (send self :basis))) ;; was cons -- why?
469 (list (+ 1 (send self :basis))))))
470 (m (send self :sweep-matrix)))
471 (format t "~%REMOVEME2: Coef-ests: ~A ~% ~A ~% ~A ~% ~A"
472 m n indices (send self :basis))
473 (coerce (compound-data-seq (select m (+ 1 n) indices)) 'list)))
475 (defmeth regression-model-proto :xtxinv ()
476 "Message args: ()
477 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
478 (let ((indices (if (send self :intercept)
479 (cons 0 (1+ (send self :basis)))
480 (1+ (send self :basis)))))
481 (select (send self :sweep-matrix) indices indices)))
483 (defmeth regression-model-proto :coef-standard-errors ()
484 "Message args: ()
485 Returns estimated standard errors of coefficients. Entries beyond the
486 intercept correspond to entries in basis."
487 (let ((s (send self :sigma-hat)))
488 (if s (* (send self :sigma-hat) (sqrt (diagonal (send self :xtxinv)))))))
490 (defmeth regression-model-proto :studentized-residuals ()
491 "Message args: ()
492 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
493 (let ((res (send self :residuals))
494 (lev (send self :leverages))
495 (sig (send self :sigma-hat))
496 (inc (send self :included)))
497 (if-else inc
498 (/ res (* sig (sqrt (pmax .00001 (- 1 lev)))))
499 (/ res (* sig (sqrt (+ 1 lev)))))))
501 (defmeth regression-model-proto :externally-studentized-residuals ()
502 "Message args: ()
503 Computes the externally studentized residuals."
504 (let* ((res (send self :studentized-residuals))
505 (df (send self :df)))
506 (if-else (send self :included)
507 (* res (sqrt (/ (- df 1) (- df (^ res 2)))))
508 res)))
510 (defmeth regression-model-proto :cooks-distances ()
511 "Message args: ()
512 Computes Cook's distances."
513 (let ((lev (send self :leverages))
514 (res (/ (^ (send self :studentized-residuals) 2)
515 (send self :num-coefs))))
516 (if-else (send self :included) (* res (/ lev (- 1 lev) )) (* res lev))))
519 (defun plot-points (x y &rest args)
520 "FIXME!!"
521 (declare (ignore x y args))
522 (error "Graphics not implemented yet."))
524 ;; Can not plot points yet!!
525 (defmeth regression-model-proto :plot-residuals (&optional x-values)
526 "Message args: (&optional x-values)
527 Opens a window with a plot of the residuals. If X-VALUES are not supplied
528 the fitted values are used. The plot can be linked to other plots with the
529 link-views function. Returns a plot object."
530 (plot-points (if x-values x-values (send self :fit-values))
531 (send self :residuals)
532 :title "Residual Plot"
533 :point-labels (send self :case-labels)))
535 (defmeth regression-model-proto :plot-bayes-residuals
536 (&optional x-values)
537 "Message args: (&optional x-values)
539 Opens a window with a plot of the standardized residuals and two
540 standard error bars for the posterior distribution of the actual
541 deviations from the line. See Chaloner and Brant. If X-VALUES are not
542 supplied the fitted values are used. The plot can be linked to other
543 plots with the link-views function. Returns a plot object."
545 (let* ((r (/ (send self :residuals)
546 (send self :sigma-hat)))
547 (d (* 2 (sqrt (send self :leverages))))
548 (low (- r d))
549 (high (+ r d))
550 (x-values (if x-values x-values (send self :fit-values)))
551 (p (plot-points x-values r
552 :title "Bayes Residual Plot"
553 :point-labels (send self :case-labels))))
554 (map 'list #'(lambda (a b c d) (send p :plotline a b c d nil))
555 x-values low x-values high)
556 (send p :adjust-to-data)