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.
21 (defpackage :lisp-stat-regression-linear
23 :lisp-stat-object-system
25 :lisp-stat-compound-data
27 (:shadowing-import-from
:lisp-stat-object-system
28 slot-value call-method call-next-method
)
30 (:export regression-model regression-model-proto x y intercept sweep-matrix
31 basis weights included total-sum-of-squares residual-sum-of-squares
32 predictor-names response-name case-labels
))
34 (in-package :lisp-stat-regression-linear
)
36 ;;; Regresion Model Prototype
38 (defproto regression-model-proto
39 '(x y intercept sweep-matrix basis weights
42 residual-sum-of-squares
48 "Normal Linear Regression Model")
50 (defun regression-model (x y
&key
54 (included (repeat t
(length y
)))
58 "Args: (x y &key (intercept T) (print T) weights
59 included predictor-names response-name case-labels)
60 X - list of independent variables or X matrix
61 Y - dependent variable.
62 INTERCEPT - T to include (default), NIL for no intercept
63 PRINT - if not NIL print summary information
64 WEIGHTS - if supplied should be the same length as Y; error variances are
65 assumed to be inversely proportional to WEIGHTS
66 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
67 - sequences of strings or symbols.
68 INCLUDED - if supplied should be the same length as Y, with elements nil
69 to skip a in computing estimates (but not in residual analysis).
70 Returns a regression model object. To examine the model further assign the
71 result to a variable and send it messages.
72 Example (data are in file absorbtion.lsp in the sample data directory/folder):
73 (def m (regression-model (list iron aluminum) absorbtion))
74 (send m :help) (send m :plot-residuals)"
77 ((vectorp x
) (list x
))
78 ((and (consp x
) (numberp (car x
))) (list x
))
80 (m (send regression-model-proto
:new
)))
81 (send m
:x
(if (matrixp x
) x
(apply #'bind-columns x
)))
83 (send m
:intercept intercept
)
84 (send m
:weights weights
)
85 (send m
:included included
)
86 (send m
:predictor-names predictor-names
)
87 (send m
:response-name response-name
)
88 (send m
:case-labels case-labels
)
89 (if print
(send m
:display
))
92 (defmeth regression-model-proto
:isnew
()
93 (send self
:needs-computing t
))
95 (defmeth regression-model-proto
:save
()
97 Returns an expression that will reconstruct the regression model."
98 `(regression-model ',(send self
:x
)
100 :intercept
',(send self
:intercept
)
101 :weights
',(send self
:weights
)
102 :included
',(send self
:included
)
103 :predictor-names
',(send self
:predictor-names
)
104 :response-name
',(send self
:response-name
)
105 :case-labels
',(send self
:case-labels
)))
107 ;;; Computing and Display Methods
109 (defmeth regression-model-proto
:compute
()
111 Recomputes the estimates. For internal use by other messages"
112 (let* ((included (if-else (send self
:included
) 1 0))
115 (intercept (send self
:intercept
))
116 (weights (send self
:weights
))
117 (w (if weights
(* included weights
) included
))
118 (m (make-sweep-matrix x y w
))
119 (n (array-dimension x
1))
120 (p (- (array-dimension m
0) 1))
122 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation
(column-list x
)))))
123 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
126 (sweep-operator m
(iseq 1 n
) tol
)
127 (sweep-operator m
(iseq 0 n
) (cons 0.0 tol
)))))
128 (setf (slot-value 'sweep-matrix
) (first sweep-result
))
129 (setf (slot-value 'total-sum-of-squares
) tss
)
130 (setf (slot-value 'residual-sum-of-squares
)
131 (aref (first sweep-result
) p p
))
132 (setf (slot-value 'basis
)
133 (let ((b (remove 0 (second sweep-result
))))
134 (if b
(- (reduce #'-
(reverse b
)) 1)
135 (error "no columns could be swept"))))))
137 (defmeth regression-model-proto
:needs-computing
(&optional set
)
138 (if set
(setf (slot-value 'sweep-matrix
) nil
))
139 (null (slot-value 'sweep-matrix
)))
141 (defmeth regression-model-proto
:display
()
143 Prints the least squares regression summary. Variables not used in the fit
144 are marked as aliased."
145 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
146 (se-s (send self
:coef-standard-errors
))
148 (p-names (send self
:predictor-names
)))
149 (if (send self
:weights
)
150 (format t
"~%Weighted Least Squares Estimates:~2%")
151 (format t
"~%Least Squares Estimates:~2%"))
152 (when (send self
:intercept
)
153 (format t
"Constant ~10f ~A~%"
154 (car coefs
) (list (car se-s
)))
155 (setf coefs
(cdr coefs
))
156 (setf se-s
(cdr se-s
)))
157 (dotimes (i (array-dimension x
1))
159 ((member i
(send self
:basis
))
160 (format t
"~22a ~10f ~A~%"
161 (select p-names i
) (car coefs
) (list (car se-s
)))
162 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
163 (t (format t
"~22a aliased~%" (select p-names i
)))))
165 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
166 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
167 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
168 (if (/= (send self
:num-cases
) (send self
:num-included
))
169 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
170 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
173 ;;; 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
))
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
))
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."
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."
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
()
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
()
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
()
227 Returns the indices of the variables used in fitting the model."
228 (if (send self
:needs-computing
) (send self
:compute
))
231 (defmeth regression-model-proto
:sweep-matrix
()
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
))
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
)
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
))
278 ;;; None of these methods access any slots directly.
281 (defmeth regression-model-proto
:num-cases
()
283 Returns the number of cases in the model."
284 (length (send self
:y
)))
286 (defmeth regression-model-proto
:num-included
()
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
()
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
()
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
()
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
)
315 (defmeth regression-model-proto
:leverages
()
317 Returns the diagonal elements of the hat matrix."
318 (let* ((weights (send self
:weights
))
319 (x (send self
:x-matrix
))
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
()
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
()
332 Returns the raw residuals for a model."
333 (- (send self
:y
) (send self
:fit-values
)))
335 (defmeth regression-model-proto
:residuals
()
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
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
()
346 Returns the error sum of squares for the model."
347 (send self
:residual-sum-of-squares
))
349 (defmeth regression-model-proto
:sigma-hat
()
351 Returns the estimated standard deviation of the deviations about the
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
()
361 Returns the sample squared multiple correlation coefficient, R squared, for
363 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
366 (defmeth regression-model-proto
:coef-estimates
()
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
()
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
()
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
()
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
)))
400 (/ res
(* sig
(sqrt (pmax .00001 (- 1 lev
)))))
401 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
403 (defmeth regression-model-proto
:externally-studentized-residuals
()
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)))))
412 (defmeth regression-model-proto
:cooks-distances
()
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
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
))))
442 (x-values (if x-values x-values
(send self
:fit-values
)))
443 (p (plot-points x-values r
444 :title
"Bayes Residual Plot"
445 :point-labels
(send self
:case-labels
))))
447 ;; the lambda needs to be something that fits into list
449 ;; #'(lambda (a b c d) (send p :plotline a b c d nil))
450 ;; x-values low x-values high)
451 (send p
:adjust-to-data
)