but not really...
[CommonLispStat.git] / regression.lsp
blob781fc6d8d7414fa103a5e306da49e5c1883fa6d9
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 (defproto regression-model-proto
49 '(x y intercept sweep-matrix basis weights
50 included
51 total-sum-of-squares
52 residual-sum-of-squares
53 predictor-names
54 response-name
55 case-labels)
57 *object*
58 "Normal Linear Regression Model")
60 (defun regression-model (x y &key
61 (intercept T)
62 (print T)
63 (weights nil)
64 (included (repeat t (length y)))
65 predictor-names
66 response-name
67 case-labels)
68 "Args: (x y &key (intercept T) (print T) (weights nil)
69 included predictor-names response-name case-labels)
70 X - list of independent variables or X matrix
71 Y - dependent variable.
72 INTERCEPT - T to include (default), NIL for no intercept
73 PRINT - if not NIL print summary information
74 WEIGHTS - if supplied should be the same length as Y; error variances are
75 assumed to be inversely proportional to WEIGHTS
76 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
77 - sequences of strings or symbols.
78 INCLUDED - if supplied should be the same length as Y, with elements nil
79 to skip a in computing estimates (but not in residual analysis).
80 Returns a regression model object. To examine the model further assign the
81 result to a variable and send it messages.
82 Example (data are in file absorbtion.lsp in the sample data directory/folder):
83 (def m (regression-model (list iron aluminum) absorbtion))
84 (send m :help) (send m :plot-residuals)"
85 (let ((x (cond
86 ((matrixp x) x)
87 ((vectorp x) (list x))
88 ((and (consp x) (numberp (car x))) (list x))
89 (t x)))
90 (m (send regression-model-proto :new)))
91 (send m :x (if (matrixp x) x (apply #'bind-columns x)))
92 (send m :y y)
93 (send m :intercept intercept)
94 (send m :weights weights)
95 (send m :included included)
96 (send m :predictor-names predictor-names)
97 (send m :response-name response-name)
98 (send m :case-labels case-labels)
99 (if print (send m :display))
102 (defmeth regression-model-proto :isnew ()
103 (send self :needs-computing t))
105 (defmeth regression-model-proto :save ()
106 "Message args: ()
107 Returns an expression that will reconstruct the regression model."
108 `(regression-model ',(send self :x)
109 ',(send self :y)
110 :intercept ',(send self :intercept)
111 :weights ',(send self :weights)
112 :included ',(send self :included)
113 :predictor-names ',(send self :predictor-names)
114 :response-name ',(send self :response-name)
115 :case-labels ',(send self :case-labels)))
117 ;;; Computing and Display Methods
119 (defmeth regression-model-proto :compute ()
120 "Message args: ()
121 Recomputes the estimates. For internal use by other messages"
122 (let* ((included (if-else (send self :included) 1 0))
123 (x (send self :x))
124 (y (send self :y))
125 (intercept (send self :intercept))
126 (weights (send self :weights))
127 (w (if weights (* included weights) included))
128 (m (make-sweep-matrix x y w))
129 (n (array-dimension x 1))
130 (p (- (array-dimension m 0) 1))
131 (tss (aref m p p))
132 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation (column-list x)))))
133 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
134 (sweep-result
135 (if intercept
136 (sweep-operator m (iseq 1 n) tol)
137 (sweep-operator m (iseq 0 n) (cons 0.0 tol)))))
138 (setf (slot-value 'sweep-matrix) (first sweep-result))
139 (setf (slot-value 'total-sum-of-squares) tss)
140 (setf (slot-value 'residual-sum-of-squares)
141 (aref (first sweep-result) p p))
142 (setf (slot-value 'basis)
143 (let ((b (remove 0 (second sweep-result))))
144 (if b (- (reduce #'- (reverse b)) 1)
145 (error "no columns could be swept"))))))
147 (defmeth regression-model-proto :needs-computing (&optional set)
148 (if set (setf (slot-value 'sweep-matrix) nil))
149 (null (slot-value 'sweep-matrix)))
151 (defmeth regression-model-proto :display ()
152 "Message args: ()
153 Prints the least squares regression summary. Variables not used in the fit
154 are marked as aliased."
155 (let ((coefs (coerce (send self :coef-estimates) 'list))
156 (se-s (send self :coef-standard-errors))
157 (x (send self :x))
158 (p-names (send self :predictor-names)))
159 (if (send self :weights)
160 (format t "~%Weighted Least Squares Estimates:~2%")
161 (format t "~%Least Squares Estimates:~2%"))
162 (when (send self :intercept)
163 (format t "Constant ~10f ~A~%"
164 (car coefs) (list (car se-s)))
165 (setf coefs (cdr coefs))
166 (setf se-s (cdr se-s)))
167 (dotimes (i (array-dimension x 1))
168 (cond
169 ((member i (send self :basis))
170 (format t "~22a ~10f ~A~%"
171 (select p-names i) (car coefs) (list (car se-s)))
172 (setf coefs (cdr coefs) se-s (cdr se-s)))
173 (t (format t "~22a aliased~%" (select p-names i)))))
174 (format t "~%")
175 (format t "R Squared: ~10f~%" (send self :r-squared))
176 (format t "Sigma hat: ~10f~%" (send self :sigma-hat))
177 (format t "Number of cases: ~10d~%" (send self :num-cases))
178 (if (/= (send self :num-cases) (send self :num-included))
179 (format t "Number of cases used: ~10d~%" (send self :num-included)))
180 (format t "Degrees of freedom: ~10d~%" (send self :df))
181 (format t "~%")))
183 ;;; Slot accessors and mutators
185 (defmeth regression-model-proto :x (&optional new-x)
186 "Message args: (&optional new-x)
187 With no argument returns the x matrix as supplied to m. With an argument
188 NEW-X sets the x matrix to NEW-X and recomputes the estimates."
189 (when (and new-x (matrixp new-x))
190 (setf (slot-value 'x) new-x)
191 (send self :needs-computing t))
192 (slot-value 'x))
194 (defmeth regression-model-proto :y (&optional new-y)
195 "Message args: (&optional new-y)
196 With no argument returns the y sequence as supplied to m. With an argument
197 NEW-Y sets the y sequence to NEW-Y and recomputes the estimates."
198 (when (and new-y (or (matrixp new-y) (sequencep new-y)))
199 (setf (slot-value 'y) new-y)
200 (send self :needs-computing t))
201 (slot-value 'y))
203 (defmeth regression-model-proto :intercept (&optional (val nil set))
204 "Message args: (&optional new-intercept)
205 With no argument returns T if the model includes an intercept term, nil if
206 not. With an argument NEW-INTERCEPT the model is changed to include or
207 exclude an intercept, according to the value of NEW-INTERCEPT."
208 (when set
209 (setf (slot-value 'intercept) val)
210 (send self :needs-computing t))
211 (slot-value 'intercept))
213 (defmeth regression-model-proto :weights (&optional (new-w nil set))
214 "Message args: (&optional new-w)
215 With no argument returns the weight sequence as supplied to m; NIL means
216 an unweighted model. NEW-W sets the weights sequence to NEW-W and
217 recomputes the estimates."
218 (when set
219 (setf (slot-value 'weights) new-w)
220 (send self :needs-computing t))
221 (slot-value 'weights))
223 (defmeth regression-model-proto :total-sum-of-squares ()
224 "Message args: ()
225 Returns the total sum of squares around the mean."
226 (if (send self :needs-computing) (send self :compute))
227 (slot-value 'total-sum-of-squares))
229 (defmeth regression-model-proto :residual-sum-of-squares ()
230 "Message args: ()
231 Returns the residual sum of squares for the model."
232 (if (send self :needs-computing) (send self :compute))
233 (slot-value 'residual-sum-of-squares))
235 (defmeth regression-model-proto :basis ()
236 "Message args: ()
237 Returns the indices of the variables used in fitting the model."
238 (if (send self :needs-computing) (send self :compute))
239 (slot-value 'basis))
241 (defmeth regression-model-proto :sweep-matrix ()
242 "Message args: ()
243 Returns the swept sweep matrix. For internal use"
244 (if (send self :needs-computing) (send self :compute))
245 (slot-value 'sweep-matrix))
247 (defmeth regression-model-proto :included (&optional new-included)
248 "Message args: (&optional new-included)
249 With no argument, NIL means a case is not used in calculating estimates, and non-nil means it is used. NEW-INCLUDED is a sequence of length of y of nil and t to select cases. Estimates are recomputed."
250 (when (and new-included
251 (= (length new-included) (send self :num-cases)))
252 (setf (slot-value 'included) (copy-seq new-included))
253 (send self :needs-computing t))
254 (if (slot-value 'included)
255 (slot-value 'included)
256 (repeat t (send self :num-cases))))
258 (defmeth regression-model-proto :predictor-names (&optional (names nil set))
259 "Message args: (&optional (names nil set))
260 With no argument returns the predictor names. NAMES sets the names."
261 (if set (setf (slot-value 'predictor-names) (mapcar #'string names)))
262 (let ((p (array-dimension (send self :x) 1))
263 (p-names (slot-value 'predictor-names)))
264 (if (not (and p-names (= (length p-names) p)))
265 (setf (slot-value 'predictor-names)
266 (mapcar #'(lambda (a) (format nil "Variable ~a" a))
267 (iseq 0 (- p 1))))))
268 (slot-value 'predictor-names))
270 (defmeth regression-model-proto :response-name (&optional (name "Y" set))
271 "Message args: (&optional name)
272 With no argument returns the response name. NAME sets the name."
273 (if set (setf (slot-value 'response-name) (if name (string name) "Y")))
274 (slot-value 'response-name))
276 (defmeth regression-model-proto :case-labels (&optional (labels nil set))
277 "Message args: (&optional labels)
278 With no argument returns the case-labels. LABELS sets the labels."
279 (if set (setf (slot-value 'case-labels)
280 (if labels
281 (mapcar #'string labels)
282 (mapcar #'(lambda (x) (format nil "~d" x))
283 (iseq 0 (- (send self :num-cases) 1))))))
284 (slot-value 'case-labels))
287 ;;; Other Methods
288 ;;; None of these methods access any slots directly.
291 (defmeth regression-model-proto :num-cases ()
292 "Message args: ()
293 Returns the number of cases in the model."
294 (length (send self :y)))
296 (defmeth regression-model-proto :num-included ()
297 "Message args: ()
298 Returns the number of cases used in the computations."
299 (sum (if-else (send self :included) 1 0)))
301 (defmeth regression-model-proto :num-coefs ()
302 "Message args: ()
303 Returns the number of coefficients in the fit model (including the
304 intercept if the model includes one)."
305 (if (send self :intercept)
306 (+ 1 (length (send self :basis)))
307 (length (send self :basis))))
309 (defmeth regression-model-proto :df ()
310 "Message args: ()
311 Returns the number of degrees of freedom in the model."
312 (- (send self :num-included) (send self :num-coefs)))
314 (defmeth regression-model-proto :x-matrix ()
315 "Message args: ()
316 Returns the X matrix for the model, including a column of 1's, if
317 appropriate. Columns of X matrix correspond to entries in basis."
318 (let ((m (select (send self :x)
319 (iseq 0 (- (send self :num-cases) 1))
320 (send self :basis))))
321 (if (send self :intercept)
322 (bind-columns (repeat 1 (send self :num-cases)) m)
323 m)))
325 (defmeth regression-model-proto :leverages ()
326 "Message args: ()
327 Returns the diagonal elements of the hat matrix."
328 (let* ((weights (send self :weights))
329 (x (send self :x-matrix))
330 (raw-levs
331 (matmult (* (matmult x (send self :xtxinv)) x)
332 (repeat 1 (send self :num-coefs)))))
333 (if weights (* weights raw-levs) raw-levs)))
335 (defmeth regression-model-proto :fit-values ()
336 "Message args: ()
337 Returns the fitted values for the model."
338 (matmult (send self :x-matrix) (send self :coef-estimates)))
340 (defmeth regression-model-proto :raw-residuals ()
341 "Message args: ()
342 Returns the raw residuals for a model."
343 (- (send self :y) (send self :fit-values)))
345 (defmeth regression-model-proto :residuals ()
346 "Message args: ()
347 Returns the raw residuals for a model without weights. If the model
348 includes weights the raw residuals times the square roots of the weights
349 are returned."
350 (let ((raw-residuals (send self :raw-residuals))
351 (weights (send self :weights)))
352 (if weights (* (sqrt weights) raw-residuals) raw-residuals)))
354 (defmeth regression-model-proto :sum-of-squares ()
355 "Message args: ()
356 Returns the error sum of squares for the model."
357 (send self :residual-sum-of-squares))
359 (defmeth regression-model-proto :sigma-hat ()
360 "Message args: ()
361 Returns the estimated standard deviation of the deviations about the
362 regression line."
363 (let ((ss (send self :sum-of-squares))
364 (df (send self :df)))
365 (if (/= df 0) (sqrt (/ ss df)))))
367 ;; for models without an intercept the 'usual' formula for R^2 can give
368 ;; negative results; hence the max.
369 (defmeth regression-model-proto :r-squared ()
370 "Message args: ()
371 Returns the sample squared multiple correlation coefficient, R squared, for
372 the regression."
373 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
376 (defmeth regression-model-proto :coef-estimates ()
377 "Message args: ()
378 Returns the OLS (ordinary least squares) estimates of the regression
379 coefficients. Entries beyond the intercept correspond to entries in basis."
380 (let ((n (array-dimension (send self :x) 1))
381 (indices (if (send self :intercept)
382 (cons 0 (+ 1 (send self :basis)))
383 (+ 1 (send self :basis))))
384 (m (send self :sweep-matrix)))
385 (coerce (compound-data-seq (select m (+ 1 n) indices)) 'list)))
387 (defmeth regression-model-proto :xtxinv ()
388 "Message args: ()
389 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
390 (let ((indices (if (send self :intercept)
391 (cons 0 (1+ (send self :basis)))
392 (1+ (send self :basis)))))
393 (select (send self :sweep-matrix) indices indices)))
395 (defmeth regression-model-proto :coef-standard-errors ()
396 "Message args: ()
397 Returns estimated standard errors of coefficients. Entries beyond the
398 intercept correspond to entries in basis."
399 (let ((s (send self :sigma-hat)))
400 (if s (* (send self :sigma-hat) (sqrt (diagonal (send self :xtxinv)))))))
402 (defmeth regression-model-proto :studentized-residuals ()
403 "Message args: ()
404 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
405 (let ((res (send self :residuals))
406 (lev (send self :leverages))
407 (sig (send self :sigma-hat))
408 (inc (send self :included)))
409 (if-else inc
410 (/ res (* sig (sqrt (pmax .00001 (- 1 lev)))))
411 (/ res (* sig (sqrt (+ 1 lev)))))))
413 (defmeth regression-model-proto :externally-studentized-residuals ()
414 "Message args: ()
415 Computes the externally studentized residuals."
416 (let* ((res (send self :studentized-residuals))
417 (df (send self :df)))
418 (if-else (send self :included)
419 (* res (sqrt (/ (- df 1) (- df (^ res 2)))))
420 res)))
422 (defmeth regression-model-proto :cooks-distances ()
423 "Message args: ()
424 Computes Cook's distances."
425 (let ((lev (send self :leverages))
426 (res (/ (^ (send self :studentized-residuals) 2)
427 (send self :num-coefs))))
428 (if-else (send self :included) (* res (/ lev (- 1 lev) )) (* res lev))))
431 (defun plot-points (x y &rest args)
432 "FIXME!!"
433 (declare (ignore x y))
434 (error "Graphics not implemented yet."))
436 ;; Can not plot points yet!!
437 (defmeth regression-model-proto :plot-residuals (&optional x-values)
438 "Message args: (&optional x-values)
439 Opens a window with a plot of the residuals. If X-VALUES are not supplied
440 the fitted values are used. The plot can be linked to other plots with the
441 link-views function. Returns a plot object."
442 (plot-points (if x-values x-values (send self :fit-values))
443 (send self :residuals)
444 :title "Residual Plot"
445 :point-labels (send self :case-labels)))
447 (defmeth regression-model-proto :plot-bayes-residuals
448 (&optional x-values)
449 "Message args: (&optional x-values)
450 Opens a window with a plot of the standardized residuals and two standard
451 error bars for the posterior distribution of the actual deviations from the
452 line. See Chaloner and Brant. If X-VALUES are not supplied the fitted values
453 are used. The plot can be linked to other plots with the link-views function.
454 Returns a plot object."
455 (let* ((r (/ (send self :residuals) (send self :sigma-hat)))
456 (d (* 2 (sqrt (send self :leverages))))
457 (low (- r d))
458 (high (+ r d))
459 (x-values (if x-values x-values (send self :fit-values)))
460 (p (plot-points x-values r
461 :title "Bayes Residual Plot"
462 :point-labels (send self :case-labels))))
463 (map 'list #'(lambda (a b c d) (send p :plotline a b c d nil))
464 x-values low x-values high)
465 (send p :adjust-to-data)