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