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