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
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.
16 ;;;; Incorporates modifications suggested by Sandy Weisberg.
19 (defpackage :lisp-stat-regression-linear
21 :lisp-stat-object-system
23 :lisp-stat-compound-data
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
41 residual-sum-of-squares
47 "Normal Linear Regression Model")
49 (defun regression-model (x y
&key
53 (included (repeat t
(length y
)))
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)"
76 ((vectorp x
) (list x
))
77 ((and (consp x
) (numberp (car x
))) (list x
))
79 (m (send regression-model-proto
:new
)))
80 (send m
:x
(if (matrixp x
) x
(apply #'bind-columns x
)))
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
))
91 (defmeth regression-model-proto
:isnew
()
92 (send self
:needs-computing t
))
94 (defmeth regression-model-proto
:save
()
96 Returns an expression that will reconstruct the regression model."
97 `(regression-model ',(send self
:x
)
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
()
110 Recomputes the estimates. For internal use by other messages"
111 (let* ((included (if-else (send self
:included
) 1 0))
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))
121 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation
(column-list x
)))))
122 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
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
()
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
))
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))
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
)))))
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
))
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
))
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
))
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."
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."
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
()
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
()
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
()
226 Returns the indices of the variables used in fitting the model."
227 (if (send self
:needs-computing
) (send self
:compute
))
230 (defmeth regression-model-proto
:sweep-matrix
()
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
))
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
)
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
))
277 ;;; None of these methods access any slots directly.
280 (defmeth regression-model-proto
:num-cases
()
282 Returns the number of cases in the model."
283 (length (send self
:y
)))
285 (defmeth regression-model-proto
:num-included
()
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
()
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
()
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
()
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
)
314 (defmeth regression-model-proto
:leverages
()
316 Returns the diagonal elements of the hat matrix."
317 (let* ((weights (send self
:weights
))
318 (x (send self
:x-matrix
))
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
()
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
()
331 Returns the raw residuals for a model."
332 (- (send self
:y
) (send self
:fit-values
)))
334 (defmeth regression-model-proto
:residuals
()
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
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
()
345 Returns the error sum of squares for the model."
346 (send self
:residual-sum-of-squares
))
348 (defmeth regression-model-proto
:sigma-hat
()
350 Returns the estimated standard deviation of the deviations about the
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
()
360 Returns the sample squared multiple correlation coefficient, R squared, for
362 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
365 (defmeth regression-model-proto
:coef-estimates
()
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
()
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
()
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
()
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
)))
399 (/ res
(* sig
(sqrt (pmax .00001 (- 1 lev
)))))
400 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
402 (defmeth regression-model-proto
:externally-studentized-residuals
()
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)))))
411 (defmeth regression-model-proto
:cooks-distances
()
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
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
))))
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
))))
446 ;; the lambda needs to be something that fits into 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
)