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
24 :lisp-stat-object-system
26 :lisp-stat-compound-data
30 :lisp-stat-descriptive-statistics
)
31 (:shadowing-import-from
:lisp-stat-object-system
32 slot-value call-method call-next-method
)
33 (:shadowing-import-from
:lisp-stat-math
34 expt
+ -
* / ** mod rem abs
1+ 1- log exp sqrt sin cos tan
35 asin acos atan sinh cosh tanh asinh acosh atanh float random
36 truncate floor ceiling round minusp zerop plusp evenp oddp
37 < <= = /= >= > ;; complex
38 conjugate realpart imagpart phase
39 min max logand logior logxor lognot ffloor fceiling
40 ftruncate fround signum cis
)
41 (:export regression-model regression-model-proto x y intercept sweep-matrix
42 basis weights included total-sum-of-squares residual-sum-of-squares
43 predictor-names response-name case-labels
))
45 (in-package :lisp-stat-regression-linear
)
47 ;;; Regresion Model Prototype
49 (defvar regression-model-proto nil
50 "Prototype for all regression model instances.")
51 (defproto regression-model-proto
52 '(x y intercept sweep-matrix basis weights
55 residual-sum-of-squares
62 "Normal Linear Regression Model")
64 (defun regression-model (x y
&key
68 (included (repeat t
(length y
)))
72 (doc "Undocumented Regression Model Instance")
74 "Args: (x y &key (intercept T) (print T) (weights nil)
75 included predictor-names response-name case-labels)
76 X - list of independent variables or X matrix
77 Y - dependent variable.
78 INTERCEPT - T to include (default), NIL for no intercept
79 PRINT - if not NIL print summary information
80 WEIGHTS - if supplied should be the same length as Y; error
82 assumed to be inversely proportional to WEIGHTS
83 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
84 - sequences of strings or symbols.
85 INCLUDED - if supplied should be the same length as Y, with
86 elements nil to skip a in computing estimates (but not
87 in residual analysis).
88 Returns a regression model object. To examine the model further assign the
89 result to a variable and send it messages.
90 Example (data are in file absorbtion.lsp in the sample data directory):
91 (def m (regression-model (list iron aluminum) absorbtion))
92 (send m :help) (send m :plot-residuals)"
95 ((typep x
'vector
) (list x
))
97 (numberp (car x
))) (list x
))
99 (m (send regression-model-proto
:new
)))
102 (send m
:x
(if (matrixp x
) x
(apply #'bind-columns x
)))
104 (send m
:intercept intercept
)
105 (send m
:weights weights
)
106 (send m
:included included
)
107 (send m
:predictor-names predictor-names
)
108 (send m
:response-name response-name
)
109 (send m
:case-labels case-labels
)
113 (format t
"~S~%" (send m
:doc
))
114 (format t
"X: ~S~%" (send m
:x
))
115 (format t
"Y: ~S~%" (send m
:y
))))
116 (if print
(send m
:display
))
119 (defmeth regression-model-proto
:isnew
()
120 (send self
:needs-computing t
))
122 (defmeth regression-model-proto
:save
()
124 Returns an expression that will reconstruct the regression model."
125 `(regression-model ',(send self
:x
)
127 :intercept
',(send self
:intercept
)
128 :weights
',(send self
:weights
)
129 :included
',(send self
:included
)
130 :predictor-names
',(send self
:predictor-names
)
131 :response-name
',(send self
:response-name
)
132 :case-labels
',(send self
:case-labels
)))
134 ;;; Computing and Display Methods
136 (defmeth regression-model-proto
:compute
()
138 Recomputes the estimates. For internal use by other messages"
139 (let* ((included (if-else (send self
:included
) 1 0))
142 (intercept (send self
:intercept
))
143 (weights (send self
:weights
))
144 (w (if weights
(* included weights
) included
))
145 (m (make-sweep-matrix x y w
)) ;;; ERROR HERE
146 (n (array-dimension x
1))
147 (p (- (array-dimension m
0) 1))
149 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation
(column-list x
)))))
150 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
153 (sweep-operator m
(iseq 1 n
) tol
)
154 (sweep-operator m
(iseq 0 n
) (cons 0.0 tol
)))))
155 (setf (slot-value 'sweep-matrix
) (first sweep-result
))
156 (setf (slot-value 'total-sum-of-squares
) tss
)
157 (setf (slot-value 'residual-sum-of-squares
)
158 (aref (first sweep-result
) p p
))
159 (setf (slot-value 'basis
)
160 (let ((b (remove 0 (second sweep-result
))))
161 (if b
(- (reduce #'-
(reverse b
)) 1)
162 (error "no columns could be swept"))))))
164 (defmeth regression-model-proto
:needs-computing
(&optional set
)
165 ;;(declare (ignore self))
166 (if set
(setf (slot-value 'sweep-matrix
) nil
))
167 (null (slot-value 'sweep-matrix
)))
169 (defmeth regression-model-proto
:display
()
171 Prints the least squares regression summary. Variables not used in the fit
172 are marked as aliased."
173 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
174 (se-s (send self
:coef-standard-errors
))
176 (p-names (send self
:predictor-names
)))
177 (if (send self
:weights
)
178 (format t
"~%Weighted Least Squares Estimates:~2%")
179 (format t
"~%Least Squares Estimates:~2%"))
180 (when (send self
:intercept
)
181 (format t
"Constant ~10f ~A~%"
182 (car coefs
) (list (car se-s
)))
183 (setf coefs
(cdr coefs
))
184 (setf se-s
(cdr se-s
)))
185 (dotimes (i (array-dimension x
1))
187 ((member i
(send self
:basis
))
188 (format t
"~22a ~10f ~A~%"
189 (select p-names i
) (car coefs
) (list (car se-s
)))
190 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
191 (t (format t
"~22a aliased~%" (select p-names i
)))))
193 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
194 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
195 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
196 (if (/= (send self
:num-cases
) (send self
:num-included
))
197 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
198 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
201 ;;; Slot accessors and mutators
203 (defmeth regression-model-proto
:doc
(&optional new-doc
)
204 "Message args: (&optional new-doc)
205 With no argument returns the DOC-STRING as supplied to m. With an argument
206 NEW-DOC sets the DOC-STRING to NEW-DOC."
207 (when (and new-doc
(stringp new-doc
))
208 (setf (slot-value 'doc
) new-doc
))
212 (defmeth regression-model-proto
:x
(&optional new-x
)
213 "Message args: (&optional new-x)
214 With no argument returns the x matrix as supplied to m. With an argument
215 NEW-X sets the x matrix to NEW-X and recomputes the estimates."
216 (when (and new-x
(matrixp new-x
))
217 (setf (slot-value 'x
) new-x
)
218 (send self
:needs-computing t
))
221 (defmeth regression-model-proto
:y
(&optional new-y
)
222 "Message args: (&optional new-y)
223 With no argument returns the y sequence as supplied to m. With an argument
224 NEW-Y sets the y sequence to NEW-Y and recomputes the estimates."
226 (or (matrixp new-y
) (typep new-y
'sequence
)))
227 (setf (slot-value 'y
) new-y
)
228 (send self
:needs-computing t
))
231 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
232 "Message args: (&optional new-intercept)
233 With no argument returns T if the model includes an intercept term, nil if
234 not. With an argument NEW-INTERCEPT the model is changed to include or
235 exclude an intercept, according to the value of NEW-INTERCEPT."
237 (setf (slot-value 'intercept
) val
)
238 (send self
:needs-computing t
))
239 (slot-value 'intercept
))
241 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
242 "Message args: (&optional new-w)
243 With no argument returns the weight sequence as supplied to m; NIL means
244 an unweighted model. NEW-W sets the weights sequence to NEW-W and
245 recomputes the estimates."
247 (setf (slot-value 'weights
) new-w
)
248 (send self
:needs-computing t
))
249 (slot-value 'weights
))
251 (defmeth regression-model-proto
:total-sum-of-squares
()
253 Returns the total sum of squares around the mean."
254 (if (send self
:needs-computing
) (send self
:compute
))
255 (slot-value 'total-sum-of-squares
))
257 (defmeth regression-model-proto
:residual-sum-of-squares
()
259 Returns the residual sum of squares for the model."
260 (if (send self
:needs-computing
) (send self
:compute
))
261 (slot-value 'residual-sum-of-squares
))
263 (defmeth regression-model-proto
:basis
()
266 Returns the indices of the variables used in fitting the model, in a
268 (if (send self
:needs-computing
)
269 (send self
:compute
))
270 (if (typep (slot-value 'basis
) 'sequence
)
272 (list (slot-value 'basis
))))
277 (defmeth regression-model-proto
:sweep-matrix
()
279 Returns the swept sweep matrix. For internal use"
280 (if (send self
:needs-computing
) (send self
:compute
))
281 (slot-value 'sweep-matrix
))
283 (defmeth regression-model-proto
:included
(&optional new-included
)
284 "Message args: (&optional new-included)
286 With no argument, NIL means a case is not used in calculating
287 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
288 of length of y of nil and t to select cases. Estimates are
290 (when (and new-included
291 (= (length new-included
) (send self
:num-cases
)))
292 (setf (slot-value 'included
) (copy-seq new-included
))
293 (send self
:needs-computing t
))
294 (if (slot-value 'included
)
295 (slot-value 'included
)
296 (repeat t
(send self
:num-cases
))))
298 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
299 "Message args: (&optional (names nil set))
300 With no argument returns the predictor names. NAMES sets the names."
301 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
302 (let ((p (array-dimension (send self
:x
) 1))
303 (p-names (slot-value 'predictor-names
)))
304 (if (not (and p-names
(= (length p-names
) p
)))
305 (setf (slot-value 'predictor-names
)
306 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
308 (slot-value 'predictor-names
))
310 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
311 "Message args: (&optional name)
312 With no argument returns the response name. NAME sets the name."
313 ;;(declare (ignore self))
314 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
315 (slot-value 'response-name
))
317 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
318 "Message args: (&optional labels)
319 With no argument returns the case-labels. LABELS sets the labels."
320 (if set
(setf (slot-value 'case-labels
)
322 (mapcar #'string labels
)
323 (mapcar #'(lambda (x) (format nil
"~d" x
))
324 (iseq 0 (- (send self
:num-cases
) 1))))))
325 (slot-value 'case-labels
))
329 ;;; None of these methods access any slots directly.
332 (defmeth regression-model-proto
:num-cases
()
334 Returns the number of cases in the model."
335 (length (send self
:y
)))
337 (defmeth regression-model-proto
:num-included
()
339 Returns the number of cases used in the computations."
340 (sum (if-else (send self
:included
) 1 0)))
342 (defmeth regression-model-proto
:num-coefs
()
344 Returns the number of coefficients in the fit model (including the
345 intercept if the model includes one)."
346 (if (send self
:intercept
)
347 (+ 1 (length (send self
:basis
)))
348 (length (send self
:basis
))))
350 (defmeth regression-model-proto
:df
()
352 Returns the number of degrees of freedom in the model."
353 (- (send self
:num-included
) (send self
:num-coefs
)))
355 (defmeth regression-model-proto
:x-matrix
()
357 Returns the X matrix for the model, including a column of 1's, if
358 appropriate. Columns of X matrix correspond to entries in basis."
359 (let ((m (select (send self
:x
)
360 (iseq 0 (- (send self
:num-cases
) 1))
361 (send self
:basis
))))
362 (if (send self
:intercept
)
363 (bind-columns (repeat 1 (send self
:num-cases
)) m
)
366 (defmeth regression-model-proto
:leverages
()
368 Returns the diagonal elements of the hat matrix."
369 (let* ((weights (send self
:weights
))
370 (x (send self
:x-matrix
))
372 (matmult (* (matmult x
(send self
:xtxinv
)) x
)
373 (repeat 1 (send self
:num-coefs
)))))
374 (if weights
(* weights raw-levs
) raw-levs
)))
376 (defmeth regression-model-proto
:fit-values
()
378 Returns the fitted values for the model."
379 (matmult (send self
:x-matrix
) (send self
:coef-estimates
)))
381 (defmeth regression-model-proto
:raw-residuals
()
383 Returns the raw residuals for a model."
384 (- (send self
:y
) (send self
:fit-values
)))
386 (defmeth regression-model-proto
:residuals
()
388 Returns the raw residuals for a model without weights. If the model
389 includes weights the raw residuals times the square roots of the weights
391 (let ((raw-residuals (send self
:raw-residuals
))
392 (weights (send self
:weights
)))
393 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
395 (defmeth regression-model-proto
:sum-of-squares
()
397 Returns the error sum of squares for the model."
398 (send self
:residual-sum-of-squares
))
400 (defmeth regression-model-proto
:sigma-hat
()
402 Returns the estimated standard deviation of the deviations about the
404 (let ((ss (send self
:sum-of-squares
))
405 (df (send self
:df
)))
406 (if (/= df
0) (sqrt (/ ss df
)))))
408 ;; for models without an intercept the 'usual' formula for R^2 can give
409 ;; negative results; hence the max.
410 (defmeth regression-model-proto
:r-squared
()
412 Returns the sample squared multiple correlation coefficient, R squared, for
414 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
417 (defmeth regression-model-proto
:coef-estimates
()
420 Returns the OLS (ordinary least squares) estimates of the regression
421 coefficients. Entries beyond the intercept correspond to entries in
423 (let ((n (array-dimension (send self
:x
) 1))
424 (indices (flatten-list
425 (if (send self
:intercept
)
426 (list 0 (+ 1 (send self
:basis
))) ;; was cons -- why?
427 (list (+ 1 (send self
:basis
))))))
428 (m (send self
:sweep-matrix
)))
429 (coerce (compound-data-seq (select m
(+ 1 n
) indices
)) 'list
)))
431 (defmeth regression-model-proto
:xtxinv
()
433 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
434 (let ((indices (if (send self
:intercept
)
435 (cons 0 (1+ (send self
:basis
)))
436 (1+ (send self
:basis
)))))
437 (select (send self
:sweep-matrix
) indices indices
)))
439 (defmeth regression-model-proto
:coef-standard-errors
()
441 Returns estimated standard errors of coefficients. Entries beyond the
442 intercept correspond to entries in basis."
443 (let ((s (send self
:sigma-hat
)))
444 (if s
(* (send self
:sigma-hat
) (sqrt (diagonal (send self
:xtxinv
)))))))
446 (defmeth regression-model-proto
:studentized-residuals
()
448 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
449 (let ((res (send self
:residuals
))
450 (lev (send self
:leverages
))
451 (sig (send self
:sigma-hat
))
452 (inc (send self
:included
)))
454 (/ res
(* sig
(sqrt (pmax .00001 (- 1 lev
)))))
455 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
457 (defmeth regression-model-proto
:externally-studentized-residuals
()
459 Computes the externally studentized residuals."
460 (let* ((res (send self
:studentized-residuals
))
461 (df (send self
:df
)))
462 (if-else (send self
:included
)
463 (* res
(sqrt (/ (- df
1) (- df
(^ res
2)))))
466 (defmeth regression-model-proto
:cooks-distances
()
468 Computes Cook's distances."
469 (let ((lev (send self
:leverages
))
470 (res (/ (^
(send self
:studentized-residuals
) 2)
471 (send self
:num-coefs
))))
472 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
475 (defun plot-points (x y
&rest args
)
477 (declare (ignore x y args
))
478 (error "Graphics not implemented yet."))
480 ;; Can not plot points yet!!
481 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
482 "Message args: (&optional x-values)
483 Opens a window with a plot of the residuals. If X-VALUES are not supplied
484 the fitted values are used. The plot can be linked to other plots with the
485 link-views function. Returns a plot object."
486 (plot-points (if x-values x-values
(send self
:fit-values
))
487 (send self
:residuals
)
488 :title
"Residual Plot"
489 :point-labels
(send self
:case-labels
)))
491 (defmeth regression-model-proto
:plot-bayes-residuals
493 "Message args: (&optional x-values)
495 Opens a window with a plot of the standardized residuals and two
496 standard error bars for the posterior distribution of the actual
497 deviations from the line. See Chaloner and Brant. If X-VALUES are not
498 supplied the fitted values are used. The plot can be linked to other
499 plots with the link-views function. Returns a plot object."
501 (let* ((r (/ (send self
:residuals
)
502 (send self
:sigma-hat
)))
503 (d (* 2 (sqrt (send self
:leverages
))))
506 (x-values (if x-values x-values
(send self
:fit-values
)))
507 (p (plot-points x-values r
508 :title
"Bayes Residual Plot"
509 :point-labels
(send self
:case-labels
))))
510 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
511 x-values low x-values high
)
512 (send p
:adjust-to-data
)