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