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