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