more object system refactoring
[tsl.git] / regression.lsp
blobaf0135f94340e9ca1fa6928882500a82591edcc0
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 :lisp-stat)
21 (export '(regression-model regression-model-proto x y intercept sweep-matrix
22 basis weights included total-sum-of-squares residual-sum-of-squares
23 predictor-names response-name case-labels))
25 ;;;;
26 ;;;;
27 ;;;; Regresion Model Prototype
28 ;;;;
29 ;;;;
31 (defproto regression-model-proto
32 '(x y intercept sweep-matrix basis weights
33 included
34 total-sum-of-squares
35 residual-sum-of-squares
36 predictor-names
37 response-name
38 case-labels)
40 *object*
41 "Normal Linear Regression Model")
43 ;; The doc for this function string is at the limit of XLISP's string
44 ;; constant size - making it longer may cause problems
45 (defun regression-model (x y &key
46 (intercept T)
47 (print T)
48 weights
49 (included (repeat t (length y)))
50 predictor-names
51 response-name
52 case-labels)
53 "Args: (x y &key (intercept T) (print T) weights
54 included predictor-names response-name case-labels)
55 X - list of independent variables or X matrix
56 Y - dependent variable.
57 INTERCEPT - T to include (default), NIL for no intercept
58 PRINT - if not NIL print summary information
59 WEIGHTS - if supplied should be the same length as Y; error variances are
60 assumed to be inversely proportional to WEIGHTS
61 PREDICTOR-NAMES
62 RESPONSE-NAME
63 CASE-LABELS - sequences of strings or symbols.
64 INCLUDED - if supplied should be the same length as Y, with elements nil
65 to skip a in computing estimates (but not in residual analysis).
66 Returns a regression model object. To examine the model further assign the
67 result to a variable and send it messages.
68 Example (data are in file absorbtion.lsp in the sample data directory/folder):
69 (def m (regression-model (list iron aluminum) absorbtion))
70 (send m :help)
71 (send m :plot-residuals)"
72 (let ((x (cond
73 ((matrixp x) x)
74 ((vectorp x) (list x))
75 ((and (consp x) (numberp (car x))) (list x))
76 (t x)))
77 (m (send regression-model-proto :new)))
78 (send m :x (if (matrixp x) x (apply #'bind-columns x)))
79 (send m :y y)
80 (send m :intercept intercept)
81 (send m :weights weights)
82 (send m :included included)
83 (send m :predictor-names predictor-names)
84 (send m :response-name response-name)
85 (send m :case-labels case-labels)
86 (if print (send m :display))
87 m))
89 (defmeth regression-model-proto :isnew () (send self :needs-computing t))
91 (defmeth regression-model-proto :save ()
92 "Message args: ()
93 Returns an expression that will reconstruct the regression model."
94 `(regression-model ',(send self :x)
95 ',(send self :y)
96 :intercept ',(send self :intercept)
97 :weights ',(send self :weights)
98 :included ',(send self :included)
99 :predictor-names ',(send self :predictor-names)
100 :response-name ',(send self :response-name)
101 :case-labels ',(send self :case-labels)))
104 ;;; 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 "~%")))
172 ;;; Slot accessors and mutators
175 (defmeth regression-model-proto :x (&optional new-x)
176 "Message args: (&optional new-x)
177 With no argument returns the x matrix as supplied to m. With an argument
178 NEW-X sets the x matrix to NEW-X and recomputes the estimates."
179 (when (and new-x (matrixp new-x))
180 (setf (slot-value 'x) new-x)
181 (send self :needs-computing t))
182 (slot-value 'x))
184 (defmeth regression-model-proto :y (&optional new-y)
185 "Message args: (&optional new-y)
186 With no argument returns the y sequence as supplied to m. With an argument
187 NEW-Y sets the y sequence to NEW-Y and recomputes the estimates."
188 (when (and new-y (or (matrixp new-y) (sequencep new-y)))
189 (setf (slot-value 'y) new-y)
190 (send self :needs-computing t))
191 (slot-value 'y))
193 (defmeth regression-model-proto :intercept (&optional (val nil set))
194 "Message args: (&optional new-intercept)
195 With no argument returns T if the model includes an intercept term, nil if
196 not. With an argument NEW-INTERCEPT the model is changed to include or
197 exclude an intercept, according to the value of NEW-INTERCEPT."
198 (when set
199 (setf (slot-value 'intercept) val)
200 (send self :needs-computing t))
201 (slot-value 'intercept))
203 (defmeth regression-model-proto :weights (&optional (new-w nil set))
204 "Message args: (&optional new-w)
205 With no argument returns the weight sequence as supplied to m; NIL means
206 an unweighted model. NEW-W sets the weights sequence to NEW-W and
207 recomputes the estimates."
208 (when set
209 (setf (slot-value 'weights) new-w)
210 (send self :needs-computing t))
211 (slot-value 'weights))
213 (defmeth regression-model-proto :total-sum-of-squares ()
214 "Message args: ()
215 Returns the total sum of squares around the mean."
216 (if (send self :needs-computing) (send self :compute))
217 (slot-value 'total-sum-of-squares))
219 (defmeth regression-model-proto :residual-sum-of-squares ()
220 "Message args: ()
221 Returns the residual sum of squares for the model."
222 (if (send self :needs-computing) (send self :compute))
223 (slot-value 'residual-sum-of-squares))
225 (defmeth regression-model-proto :basis ()
226 "Message args: ()
227 Returns the indices of the variables used in fitting the model."
228 (if (send self :needs-computing) (send self :compute))
229 (slot-value 'basis))
231 (defmeth regression-model-proto :sweep-matrix ()
232 "Message args: ()
233 Returns the swept sweep matrix. For internal use"
234 (if (send self :needs-computing) (send self :compute))
235 (slot-value 'sweep-matrix))
237 (defmeth regression-model-proto :included (&optional new-included)
238 "Message args: (&optional new-included)
239 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."
240 (when (and new-included
241 (= (length new-included) (send self :num-cases)))
242 (setf (slot-value 'included) (copy-seq new-included))
243 (send self :needs-computing t))
244 (if (slot-value 'included)
245 (slot-value 'included)
246 (repeat t (send self :num-cases))))
248 (defmeth regression-model-proto :predictor-names (&optional (names nil set))
249 "Message args: (&optional (names nil set))
250 With no argument returns the predictor names. NAMES sets the names."
251 (if set (setf (slot-value 'predictor-names) (mapcar #'string names)))
252 (let ((p (array-dimension (send self :x) 1))
253 (p-names (slot-value 'predictor-names)))
254 (if (not (and p-names (= (length p-names) p)))
255 (setf (slot-value 'predictor-names)
256 (mapcar #'(lambda (a) (format nil "Variable ~a" a))
257 (iseq 0 (- p 1))))))
258 (slot-value 'predictor-names))
260 (defmeth regression-model-proto :response-name (&optional (name "Y" set))
261 "Message args: (&optional name)
262 With no argument returns the response name. NAME sets the name."
263 (if set (setf (slot-value 'response-name) (if name (string name) "Y")))
264 (slot-value 'response-name))
266 (defmeth regression-model-proto :case-labels (&optional (labels nil set))
267 "Message args: (&optional labels)
268 With no argument returns the case-labels. LABELS sets the labels."
269 (if set (setf (slot-value 'case-labels)
270 (if labels
271 (mapcar #'string labels)
272 (mapcar #'(lambda (x) (format nil "~d" x))
273 (iseq 0 (- (send self :num-cases) 1))))))
274 (slot-value 'case-labels))
277 ;;; Other Methods
278 ;;; None of these methods access any slots directly.
281 (defmeth regression-model-proto :num-cases ()
282 "Message args: ()
283 Returns the number of cases in the model."
284 (length (send self :y)))
286 (defmeth regression-model-proto :num-included ()
287 "Message args: ()
288 Returns the number of cases used in the computations."
289 (sum (if-else (send self :included) 1 0)))
291 (defmeth regression-model-proto :num-coefs ()
292 "Message args: ()
293 Returns the number of coefficients in the fit model (including the
294 intercept if the model includes one)."
295 (if (send self :intercept)
296 (+ 1 (length (send self :basis)))
297 (length (send self :basis))))
299 (defmeth regression-model-proto :df ()
300 "Message args: ()
301 Returns the number of degrees of freedom in the model."
302 (- (send self :num-included) (send self :num-coefs)))
304 (defmeth regression-model-proto :x-matrix ()
305 "Message args: ()
306 Returns the X matrix for the model, including a column of 1's, if
307 appropriate. Columns of X matrix correspond to entries in basis."
308 (let ((m (select (send self :x)
309 (iseq 0 (- (send self :num-cases) 1))
310 (send self :basis))))
311 (if (send self :intercept)
312 (bind-columns (repeat 1 (send self :num-cases)) m)
313 m)))
315 (defmeth regression-model-proto :leverages ()
316 "Message args: ()
317 Returns the diagonal elements of the hat matrix."
318 (let* ((weights (send self :weights))
319 (x (send self :x-matrix))
320 (raw-levs
321 (matmult (* (matmult x (send self :xtxinv)) x)
322 (repeat 1 (send self :num-coefs)))))
323 (if weights (* weights raw-levs) raw-levs)))
325 (defmeth regression-model-proto :fit-values ()
326 "Message args: ()
327 Returns the fitted values for the model."
328 (matmult (send self :x-matrix) (send self :coef-estimates)))
330 (defmeth regression-model-proto :raw-residuals ()
331 "Message args: ()
332 Returns the raw residuals for a model."
333 (- (send self :y) (send self :fit-values)))
335 (defmeth regression-model-proto :residuals ()
336 "Message args: ()
337 Returns the raw residuals for a model without weights. If the model
338 includes weights the raw residuals times the square roots of the weights
339 are returned."
340 (let ((raw-residuals (send self :raw-residuals))
341 (weights (send self :weights)))
342 (if weights (* (sqrt weights) raw-residuals) raw-residuals)))
344 (defmeth regression-model-proto :sum-of-squares ()
345 "Message args: ()
346 Returns the error sum of squares for the model."
347 (send self :residual-sum-of-squares))
349 (defmeth regression-model-proto :sigma-hat ()
350 "Message args: ()
351 Returns the estimated standard deviation of the deviations about the
352 regression line."
353 (let ((ss (send self :sum-of-squares))
354 (df (send self :df)))
355 (if (/= df 0) (sqrt (/ ss df)))))
357 ;; for models without an intercept the 'usual' formula for R^2 can give
358 ;; negative results; hence the max.
359 (defmeth regression-model-proto :r-squared ()
360 "Message args: ()
361 Returns the sample squared multiple correlation coefficient, R squared, for
362 the regression."
363 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
366 (defmeth regression-model-proto :coef-estimates ()
367 "Message args: ()
368 Returns the OLS (ordinary least squares) estimates of the regression
369 coefficients. Entries beyond the intercept correspond to entries in basis."
370 (let ((n (array-dimension (send self :x) 1))
371 (indices (if (send self :intercept)
372 (cons 0 (+ 1 (send self :basis)))
373 (+ 1 (send self :basis))))
374 (m (send self :sweep-matrix)))
375 (coerce (compound-data-seq (select m (+ 1 n) indices)) 'list)))
377 (defmeth regression-model-proto :xtxinv ()
378 "Message args: ()
379 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
380 (let ((indices (if (send self :intercept)
381 (cons 0 (1+ (send self :basis)))
382 (1+ (send self :basis)))))
383 (select (send self :sweep-matrix) indices indices)))
385 (defmeth regression-model-proto :coef-standard-errors ()
386 "Message args: ()
387 Returns estimated standard errors of coefficients. Entries beyond the
388 intercept correspond to entries in basis."
389 (let ((s (send self :sigma-hat)))
390 (if s (* (send self :sigma-hat) (sqrt (diagonal (send self :xtxinv)))))))
392 (defmeth regression-model-proto :studentized-residuals ()
393 "Message args: ()
394 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
395 (let ((res (send self :residuals))
396 (lev (send self :leverages))
397 (sig (send self :sigma-hat))
398 (inc (send self :included)))
399 (if-else inc
400 (/ res (* sig (sqrt (pmax .00001 (- 1 lev)))))
401 (/ res (* sig (sqrt (+ 1 lev)))))))
403 (defmeth regression-model-proto :externally-studentized-residuals ()
404 "Message args: ()
405 Computes the externally studentized residuals."
406 (let* ((res (send self :studentized-residuals))
407 (df (send self :df)))
408 (if-else (send self :included)
409 (* res (sqrt (/ (- df 1) (- df (^ res 2)))))
410 res)))
412 (defmeth regression-model-proto :cooks-distances ()
413 "Message args: ()
414 Computes Cook's distances."
415 (let ((lev (send self :leverages))
416 (res (/ (^ (send self :studentized-residuals) 2)
417 (send self :num-coefs))))
418 (if-else (send self :included) (* res (/ lev (- 1 lev) )) (* res lev))))
420 (defmeth regression-model-proto :plot-residuals (&optional x-values)
421 "Message args: (&optional x-values)
422 Opens a window with a plot of the residuals. If X-VALUES are not supplied
423 the fitted values are used. The plot can be linked to other plots with the
424 link-views function. Returns a plot object."
425 (plot-points (if x-values x-values (send self :fit-values))
426 (send self :residuals)
427 :title "Residual Plot"
428 :point-labels (send self :case-labels)))
430 (defmeth regression-model-proto :plot-bayes-residuals
431 (&optional x-values)
432 "Message args: (&optional x-values)
433 Opens a window with a plot of the standardized residuals and two standard
434 error bars for the posterior distribution of the actual deviations from the
435 line. See Chaloner and Brant. If X-VALUES are not supplied the fitted values
436 are used. The plot can be linked to other plots with the link-views function.
437 Returns a plot object."
438 (let* ((r (/ (send self :residuals) (send self :sigma-hat)))
439 (d (* 2 (sqrt (send self :leverages))))
440 (low (- r d))
441 (high (+ r d))
442 (x-values (if x-values x-values (send self :fit-values)))
443 (p (plot-points x-values r :title "Bayes Residual Plot"
444 :point-labels (send self :case-labels))))
445 (map 'list #'(lambda (a b c d) (send p :plotline a b c d nil))
446 x-values low x-values high)
447 (send p :adjust-to-data)