3 ;;; Copyright (c) 2005--2008, 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.
15 ;;;; Incorporates modifications suggested by Sandy Weisberg.
19 (defpackage :lisp-stat-regression-linear
21 :lisp-stat-object-system
23 :lisp-stat-compound-data
27 :lisp-stat-descriptive-statistics
)
28 (:shadowing-import-from
:lisp-stat-object-system
29 slot-value call-method call-next-method
)
30 (:shadowing-import-from
:lisp-stat-math
31 expt
+ -
* / ** mod rem abs
1+ 1- log exp sqrt sin cos tan
32 asin acos atan sinh cosh tanh asinh acosh atanh float random
33 truncate floor ceiling round minusp zerop plusp evenp oddp
34 < <= = /= >= > ;; complex
35 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 ;; The general strategy behind the fitting of models using prototypes
47 ;; is that we need to think about want the actual fits are, and then
48 ;; the fits can be used to recompute as components are changes. One
49 ;; catch here is that we'd like some notion of trace-ability, in
50 ;; particular, there is not necessarily a fixed way to take care of the
51 ;; audit trail. save-and-die might be a means of recording the final
52 ;; approach, but we are challenged by the problem of using advice and
53 ;; other such features to capture stages and steps that are considered
54 ;; along the goals of estimating a model.
56 ;; Note that the above is a stream-of-conscience response to the
57 ;; challenge of reproducibility in the setting of prototype "on-line"
60 (defvar regression-model-proto nil
61 "Prototype for all regression model instances.")
62 (defproto regression-model-proto
63 '(x y intercept sweep-matrix basis weights
66 residual-sum-of-squares
73 "Normal Linear Regression Model")
75 (defun regression-model (x y
&key
79 (included (repeat t
(length y
)))
83 (doc "Undocumented Regression Model Instance")
85 "Args: (x y &key (intercept T) (print T) (weights nil)
86 included predictor-names response-name case-labels)
87 X - list of independent variables or X matrix
88 Y - dependent variable.
89 INTERCEPT - T to include (default), NIL for no intercept
90 PRINT - if not NIL print summary information
91 WEIGHTS - if supplied should be the same length as Y; error
93 assumed to be inversely proportional to WEIGHTS
94 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
95 - sequences of strings or symbols.
96 INCLUDED - if supplied should be the same length as Y, with
97 elements nil to skip a in computing estimates (but not
98 in residual analysis).
99 Returns a regression model object. To examine the model further assign the
100 result to a variable and send it messages.
101 Example (data are in file absorbtion.lsp in the sample data directory):
102 (def m (regression-model (list iron aluminum) absorbtion))
103 (send m :help) (send m :plot-residuals)"
106 ((typep x
'vector
) (list x
))
108 (numberp (car x
))) (list x
))
110 (m (send regression-model-proto
:new
)))
113 (send m
:x
(if (matrixp x
) x
(apply #'bind-columns x
)))
115 (send m
:intercept intercept
)
116 (send m
:weights weights
)
117 (send m
:included included
)
118 (send m
:predictor-names predictor-names
)
119 (send m
:response-name response-name
)
120 (send m
:case-labels case-labels
)
124 (format t
"~S~%" (send m
:doc
))
125 (format t
"X: ~S~%" (send m
:x
))
126 (format t
"Y: ~S~%" (send m
:y
))))
127 (if print
(send m
:display
))
130 (defmeth regression-model-proto
:isnew
()
131 (send self
:needs-computing t
))
133 (defmeth regression-model-proto
:save
()
135 Returns an expression that will reconstruct the regression model."
136 `(regression-model ',(send self
:x
)
138 :intercept
',(send self
:intercept
)
139 :weights
',(send self
:weights
)
140 :included
',(send self
:included
)
141 :predictor-names
',(send self
:predictor-names
)
142 :response-name
',(send self
:response-name
)
143 :case-labels
',(send self
:case-labels
)))
145 ;;; Computing and Display Methods
147 (defmeth regression-model-proto
:compute
()
149 Recomputes the estimates. For internal use by other messages"
150 (let* ((included (if-else (send self
:included
) 1 0))
153 (intercept (send self
:intercept
))
154 (weights (send self
:weights
))
155 (w (if weights
(* included weights
) included
))
156 (m (make-sweep-matrix x y w
)) ;;; ERROR HERE
157 (n (array-dimension x
1))
158 (p (- (array-dimension m
0) 1))
160 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation
(column-list x
)))))
161 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
164 (sweep-operator m
(iseq 1 n
) tol
)
165 (sweep-operator m
(iseq 0 n
) (cons 0.0 tol
)))))
167 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
168 sweep-result x y m tss
)
169 (setf (slot-value 'sweep-matrix
) (first sweep-result
))
170 (setf (slot-value 'total-sum-of-squares
) tss
)
171 (setf (slot-value 'residual-sum-of-squares
)
172 (aref (first sweep-result
) p p
))
173 ;; SOMETHING WRONG HERE! FIX-ME
174 (setf (slot-value 'basis
)
175 (let ((b (remove 0 (second sweep-result
))))
176 (if b
(- (reduce #'-
(reverse b
)) 1)
177 (error "no columns could be swept"))))))
179 (defmeth regression-model-proto
:needs-computing
(&optional set
)
180 "Message args: ( &optional set )
182 If value given, sets the flag for whether (re)computation is needed to
183 update the model fits."
185 (if set
(setf (slot-value 'sweep-matrix
) nil
))
186 (null (slot-value 'sweep-matrix
)))
188 (defmeth regression-model-proto
:display
()
191 Prints the least squares regression summary. Variables not used in the fit
192 are marked as aliased."
193 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
194 (se-s (send self
:coef-standard-errors
))
196 (p-names (send self
:predictor-names
)))
197 (if (send self
:weights
)
198 (format t
"~%Weighted Least Squares Estimates:~2%")
199 (format t
"~%Least Squares Estimates:~2%"))
200 (when (send self
:intercept
)
201 (format t
"Constant ~10f ~A~%"
202 (car coefs
) (list (car se-s
)))
203 (setf coefs
(cdr coefs
))
204 (setf se-s
(cdr se-s
)))
205 (dotimes (i (array-dimension x
1))
207 ((member i
(send self
:basis
))
208 (format t
"~22a ~10f ~A~%"
209 (select p-names i
) (car coefs
) (list (car se-s
)))
210 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
211 (t (format t
"~22a aliased~%" (select p-names i
)))))
213 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
214 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
215 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
216 (if (/= (send self
:num-cases
) (send self
:num-included
))
217 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
218 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
221 ;;; Slot accessors and mutators
223 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
224 "Message args: (&optional new-doc)
226 Returns the DOC-STRING as supplied to m.
227 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
228 NEW-DOC. In this setting, when APPEND is T, append NEW-DOC to DOC
229 rather than doing replacement."
231 (when (and new-doc
(stringp new-doc
))
232 (setf (slot-value 'doc
)
241 (defmeth regression-model-proto
:x
(&optional new-x
)
242 "Message args: (&optional new-x)
244 With no argument returns the x matrix as supplied to m. With an
245 argument, NEW-X sets the x matrix to NEW-X and recomputes the
247 (when (and new-x
(matrixp new-x
))
248 (setf (slot-value 'x
) new-x
)
249 (send self
:needs-computing t
))
252 (defmeth regression-model-proto
:y
(&optional new-y
)
253 "Message args: (&optional new-y)
255 With no argument returns the y sequence as supplied to m. With an
256 argument, NEW-Y sets the y sequence to NEW-Y and recomputes the
260 (typep new-y
'sequence
)))
261 (setf (slot-value 'y
) new-y
)
262 (send self
:needs-computing t
))
265 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
266 "Message args: (&optional new-intercept)
268 With no argument returns T if the model includes an intercept term,
269 nil if not. With an argument NEW-INTERCEPT the model is changed to
270 include or exclude an intercept, according to the value of
273 (setf (slot-value 'intercept
) val
)
274 (send self
:needs-computing t
))
275 (slot-value 'intercept
))
277 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
278 "Message args: (&optional new-w)
280 With no argument returns the weight sequence as supplied to m; NIL
281 means an unweighted model. NEW-W sets the weights sequence to NEW-W
282 and recomputes the estimates."
284 (setf (slot-value 'weights
) new-w
)
285 (send self
:needs-computing t
))
286 (slot-value 'weights
))
288 (defmeth regression-model-proto
:total-sum-of-squares
()
291 Returns the total sum of squares around the mean."
292 (if (send self
:needs-computing
) (send self
:compute
))
293 (slot-value 'total-sum-of-squares
))
295 (defmeth regression-model-proto
:residual-sum-of-squares
()
298 Returns the residual sum of squares for the model."
299 (if (send self
:needs-computing
) (send self
:compute
))
300 (slot-value 'residual-sum-of-squares
))
302 (defmeth regression-model-proto
:basis
()
305 Returns the indices of the variables used in fitting the model, in a
306 sequence. Recompute before this, if needed."
307 (if (send self
:needs-computing
)
308 (send self
:compute
))
309 (if (typep (slot-value 'basis
) 'sequence
)
311 (list (slot-value 'basis
))))
314 (defmeth regression-model-proto
:sweep-matrix
()
317 Returns the swept sweep matrix. For internal use"
318 (if (send self
:needs-computing
)
319 (send self
:compute
))
320 (slot-value 'sweep-matrix
))
322 (defmeth regression-model-proto
:included
(&optional new-included
)
323 "Message args: (&optional new-included)
325 With no argument, NIL means a case is not used in calculating
326 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
327 of length of y of nil and t to select cases. Estimates are
329 (when (and new-included
330 (= (length new-included
) (send self
:num-cases
)))
331 (setf (slot-value 'included
) (copy-seq new-included
))
332 (send self
:needs-computing t
))
333 (if (slot-value 'included
)
334 (slot-value 'included
)
335 (repeat t
(send self
:num-cases
))))
337 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
338 "Message args: (&optional (names nil set))
340 With no argument returns the predictor names. NAMES sets the names."
341 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
342 (let ((p (array-dimension (send self
:x
) 1))
343 (p-names (slot-value 'predictor-names
)))
344 (if (not (and p-names
(= (length p-names
) p
)))
345 (setf (slot-value 'predictor-names
)
346 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
348 (slot-value 'predictor-names
))
350 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
351 "Message args: (&optional name)
353 With no argument returns the response name. NAME sets the name."
355 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
356 (slot-value 'response-name
))
358 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
359 "Message args: (&optional labels)
360 With no argument returns the case-labels. LABELS sets the labels."
361 (if set
(setf (slot-value 'case-labels
)
363 (mapcar #'string labels
)
364 (mapcar #'(lambda (x) (format nil
"~d" x
))
365 (iseq 0 (- (send self
:num-cases
) 1))))))
366 (slot-value 'case-labels
))
370 ;;; None of these methods access any slots directly.
373 (defmeth regression-model-proto
:num-cases
()
375 Returns the number of cases in the model."
376 (length (send self
:y
)))
378 (defmeth regression-model-proto
:num-included
()
380 Returns the number of cases used in the computations."
381 (sum (if-else (send self
:included
) 1 0)))
383 (defmeth regression-model-proto
:num-coefs
()
385 Returns the number of coefficients in the fit model (including the
386 intercept if the model includes one)."
387 (if (send self
:intercept
)
388 (+ 1 (length (send self
:basis
)))
389 (length (send self
:basis
))))
391 (defmeth regression-model-proto
:df
()
393 Returns the number of degrees of freedom in the model."
394 (- (send self
:num-included
) (send self
:num-coefs
)))
396 (defmeth regression-model-proto
:x-matrix
()
398 Returns the X matrix for the model, including a column of 1's, if
399 appropriate. Columns of X matrix correspond to entries in basis."
400 (let ((m (select (send self
:x
)
401 (iseq 0 (- (send self
:num-cases
) 1))
402 (send self
:basis
))))
403 (if (send self
:intercept
)
404 (bind-columns (repeat 1 (send self
:num-cases
)) m
)
407 (defmeth regression-model-proto
:leverages
()
409 Returns the diagonal elements of the hat matrix."
410 (let* ((weights (send self
:weights
))
411 (x (send self
:x-matrix
))
413 (matmult (* (matmult x
(send self
:xtxinv
)) x
)
414 (repeat 1 (send self
:num-coefs
)))))
415 (if weights
(* weights raw-levs
) raw-levs
)))
417 (defmeth regression-model-proto
:fit-values
()
419 Returns the fitted values for the model."
420 (matmult (send self
:x-matrix
) (send self
:coef-estimates
)))
422 (defmeth regression-model-proto
:raw-residuals
()
424 Returns the raw residuals for a model."
425 (- (send self
:y
) (send self
:fit-values
)))
427 (defmeth regression-model-proto
:residuals
()
429 Returns the raw residuals for a model without weights. If the model
430 includes weights the raw residuals times the square roots of the weights
432 (let ((raw-residuals (send self
:raw-residuals
))
433 (weights (send self
:weights
)))
434 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
436 (defmeth regression-model-proto
:sum-of-squares
()
438 Returns the error sum of squares for the model."
439 (send self
:residual-sum-of-squares
))
441 (defmeth regression-model-proto
:sigma-hat
()
443 Returns the estimated standard deviation of the deviations about the
445 (let ((ss (send self
:sum-of-squares
))
446 (df (send self
:df
)))
447 (if (/= df
0) (sqrt (/ ss df
)))))
449 ;; for models without an intercept the 'usual' formula for R^2 can give
450 ;; negative results; hence the max.
451 (defmeth regression-model-proto
:r-squared
()
453 Returns the sample squared multiple correlation coefficient, R squared, for
455 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
458 (defmeth regression-model-proto
:coef-estimates
()
461 Returns the OLS (ordinary least squares) estimates of the regression
462 coefficients. Entries beyond the intercept correspond to entries in
464 (let ((n (array-dimension (send self
:x
) 1))
465 (indices (flatten-list
466 (if (send self
:intercept
)
467 (cons 0 (+ 1 (send self
:basis
)))
468 (list (+ 1 (send self
:basis
))))))
469 (m (send self
:sweep-matrix
)))
470 (format t
"~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
471 m n indices
(send self
:basis
))
472 (coerce (compound-data-seq (select m
(+ 1 n
) indices
)) 'list
))) ;; ERROR
474 (defmeth regression-model-proto
:xtxinv
()
476 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
477 (let ((indices (if (send self
:intercept
)
478 (cons 0 (1+ (send self
:basis
)))
479 (1+ (send self
:basis
)))))
480 (select (send self
:sweep-matrix
) indices indices
)))
482 (defmeth regression-model-proto
:coef-standard-errors
()
484 Returns estimated standard errors of coefficients. Entries beyond the
485 intercept correspond to entries in basis."
486 (let ((s (send self
:sigma-hat
)))
487 (if s
(* (send self
:sigma-hat
) (sqrt (diagonal (send self
:xtxinv
)))))))
489 (defmeth regression-model-proto
:studentized-residuals
()
491 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
492 (let ((res (send self
:residuals
))
493 (lev (send self
:leverages
))
494 (sig (send self
:sigma-hat
))
495 (inc (send self
:included
)))
497 (/ res
(* sig
(sqrt (pmax .00001 (- 1 lev
)))))
498 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
500 (defmeth regression-model-proto
:externally-studentized-residuals
()
502 Computes the externally studentized residuals."
503 (let* ((res (send self
:studentized-residuals
))
504 (df (send self
:df
)))
505 (if-else (send self
:included
)
506 (* res
(sqrt (/ (- df
1) (- df
(^ res
2)))))
509 (defmeth regression-model-proto
:cooks-distances
()
511 Computes Cook's distances."
512 (let ((lev (send self
:leverages
))
513 (res (/ (^
(send self
:studentized-residuals
) 2)
514 (send self
:num-coefs
))))
515 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
518 (defun plot-points (x y
&rest args
)
520 (declare (ignore x y args
))
521 (error "Graphics not implemented yet."))
523 ;; Can not plot points yet!!
524 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
525 "Message args: (&optional x-values)
526 Opens a window with a plot of the residuals. If X-VALUES are not supplied
527 the fitted values are used. The plot can be linked to other plots with the
528 link-views function. Returns a plot object."
529 (plot-points (if x-values x-values
(send self
:fit-values
))
530 (send self
:residuals
)
531 :title
"Residual Plot"
532 :point-labels
(send self
:case-labels
)))
534 (defmeth regression-model-proto
:plot-bayes-residuals
536 "Message args: (&optional x-values)
538 Opens a window with a plot of the standardized residuals and two
539 standard error bars for the posterior distribution of the actual
540 deviations from the line. See Chaloner and Brant. If X-VALUES are not
541 supplied the fitted values are used. The plot can be linked to other
542 plots with the link-views function. Returns a plot object."
544 (let* ((r (/ (send self
:residuals
)
545 (send self
:sigma-hat
)))
546 (d (* 2 (sqrt (send self
:leverages
))))
549 (x-values (if x-values x-values
(send self
:fit-values
)))
550 (p (plot-points x-values r
551 :title
"Bayes Residual Plot"
552 :point-labels
(send self
:case-labels
))))
553 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
554 x-values low x-values high
)
555 (send p
:adjust-to-data
)