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")
76 (defun regression-model (x y
&key
80 (included (repeat t
(length y
)))
84 (doc "Undocumented Regression Model Instance")
86 "Args: (x y &key (intercept T) (print T) (weights nil)
87 included predictor-names response-name case-labels)
88 X - list of independent variables or X matrix
89 Y - dependent variable.
90 INTERCEPT - T to include (default), NIL for no intercept
91 PRINT - if not NIL print summary information
92 WEIGHTS - if supplied should be the same length as Y; error
94 assumed to be inversely proportional to WEIGHTS
95 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
96 - sequences of strings or symbols.
97 INCLUDED - if supplied should be the same length as Y, with
98 elements nil to skip a in computing estimates (but not
99 in residual analysis).
100 Returns a regression model object. To examine the model further assign the
101 result to a variable and send it messages.
102 Example (data are in file absorbtion.lsp in the sample data directory):
103 (def m (regression-model (list iron aluminum) absorbtion))
104 (send m :help) (send m :plot-residuals)"
107 ((typep x
'vector
) (list x
))
109 (numberp (car x
))) (list x
))
111 (m (send regression-model-proto
:new
)))
114 (send m
:x
(if (matrixp x
) x
(apply #'bind-columns x
)))
116 (send m
:intercept intercept
)
117 (send m
:weights weights
)
118 (send m
:included included
)
119 (send m
:predictor-names predictor-names
)
120 (send m
:response-name response-name
)
121 (send m
:case-labels case-labels
)
125 (format t
"~S~%" (send m
:doc
))
126 (format t
"X: ~S~%" (send m
:x
))
127 (format t
"Y: ~S~%" (send m
:y
))))
128 (if print
(send m
:display
))
131 (defmeth regression-model-proto
:isnew
()
132 (send self
:needs-computing t
))
134 (defmeth regression-model-proto
:save
()
136 Returns an expression that will reconstruct the regression model."
137 `(regression-model ',(send self
:x
)
139 :intercept
',(send self
:intercept
)
140 :weights
',(send self
:weights
)
141 :included
',(send self
:included
)
142 :predictor-names
',(send self
:predictor-names
)
143 :response-name
',(send self
:response-name
)
144 :case-labels
',(send self
:case-labels
)))
146 ;;; Computing and Display Methods
148 (defmeth regression-model-proto
:compute
()
150 Recomputes the estimates. For internal use by other messages"
151 (let* ((included (if-else (send self
:included
) 1 0))
154 (intercept (send self
:intercept
))
155 (weights (send self
:weights
))
156 (w (if weights
(* included weights
) included
))
157 (m (make-sweep-matrix x y w
)) ;;; ERROR HERE
158 (n (array-dimension x
1))
159 (p (- (array-dimension m
0) 1))
161 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation
(column-list x
)))))
162 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
165 (sweep-operator m
(iseq 1 n
) tol
)
166 (sweep-operator m
(iseq 0 n
) (cons 0.0 tol
)))))
168 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
169 sweep-result x y m tss
)
170 (setf (slot-value 'sweep-matrix
) (first sweep-result
))
171 (setf (slot-value 'total-sum-of-squares
) tss
)
172 (setf (slot-value 'residual-sum-of-squares
)
173 (aref (first sweep-result
) p p
))
174 ;; SOMETHING WRONG HERE! FIX-ME
175 (setf (slot-value 'basis
)
176 (let ((b (remove 0 (second sweep-result
))))
177 (if b
(- (reduce #'-
(reverse b
)) 1)
178 (error "no columns could be swept"))))))
180 (defmeth regression-model-proto
:needs-computing
(&optional set
)
181 "Message args: ( &optional set )
183 If value given, sets the flag for whether (re)computation is needed to
184 update the model fits."
186 (if set
(setf (slot-value 'sweep-matrix
) nil
))
187 (null (slot-value 'sweep-matrix
)))
189 (defmeth regression-model-proto
:display
()
192 Prints the least squares regression summary. Variables not used in the fit
193 are marked as aliased."
194 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
195 (se-s (send self
:coef-standard-errors
))
197 (p-names (send self
:predictor-names
)))
198 (if (send self
:weights
)
199 (format t
"~%Weighted Least Squares Estimates:~2%")
200 (format t
"~%Least Squares Estimates:~2%"))
201 (when (send self
:intercept
)
202 (format t
"Constant ~10f ~A~%"
203 (car coefs
) (list (car se-s
)))
204 (setf coefs
(cdr coefs
))
205 (setf se-s
(cdr se-s
)))
206 (dotimes (i (array-dimension x
1))
208 ((member i
(send self
:basis
))
209 (format t
"~22a ~10f ~A~%"
210 (select p-names i
) (car coefs
) (list (car se-s
)))
211 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
212 (t (format t
"~22a aliased~%" (select p-names i
)))))
214 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
215 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
216 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
217 (if (/= (send self
:num-cases
) (send self
:num-included
))
218 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
219 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
222 ;;; Slot accessors and mutators
224 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
225 "Message args: (&optional new-doc)
227 Returns the DOC-STRING as supplied to m.
228 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
229 NEW-DOC. In this setting, when APPEND is T, append NEW-DOC to DOC
230 rather than doing replacement."
232 (when (and new-doc
(stringp new-doc
))
233 (setf (slot-value 'doc
)
242 (defmeth regression-model-proto
:x
(&optional new-x
)
243 "Message args: (&optional new-x)
245 With no argument returns the x matrix as supplied to m. With an
246 argument, NEW-X sets the x matrix to NEW-X and recomputes the
248 (when (and new-x
(matrixp new-x
))
249 (setf (slot-value 'x
) new-x
)
250 (send self
:needs-computing t
))
253 (defmeth regression-model-proto
:y
(&optional new-y
)
254 "Message args: (&optional new-y)
256 With no argument returns the y sequence as supplied to m. With an
257 argument, NEW-Y sets the y sequence to NEW-Y and recomputes the
261 (typep new-y
'sequence
)))
262 (setf (slot-value 'y
) new-y
)
263 (send self
:needs-computing t
))
266 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
267 "Message args: (&optional new-intercept)
269 With no argument returns T if the model includes an intercept term,
270 nil if not. With an argument NEW-INTERCEPT the model is changed to
271 include or exclude an intercept, according to the value of
274 (setf (slot-value 'intercept
) val
)
275 (send self
:needs-computing t
))
276 (slot-value 'intercept
))
278 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
279 "Message args: (&optional new-w)
281 With no argument returns the weight sequence as supplied to m; NIL
282 means an unweighted model. NEW-W sets the weights sequence to NEW-W
283 and recomputes the estimates."
285 (setf (slot-value 'weights
) new-w
)
286 (send self
:needs-computing t
))
287 (slot-value 'weights
))
289 (defmeth regression-model-proto
:total-sum-of-squares
()
292 Returns the total sum of squares around the mean."
293 (if (send self
:needs-computing
) (send self
:compute
))
294 (slot-value 'total-sum-of-squares
))
296 (defmeth regression-model-proto
:residual-sum-of-squares
()
299 Returns the residual sum of squares for the model."
300 (if (send self
:needs-computing
) (send self
:compute
))
301 (slot-value 'residual-sum-of-squares
))
303 (defmeth regression-model-proto
:basis
()
306 Returns the indices of the variables used in fitting the model, in a
307 sequence. Recompute before this, if needed."
308 (if (send self
:needs-computing
)
309 (send self
:compute
))
310 (if (typep (slot-value 'basis
) 'sequence
)
312 (list (slot-value 'basis
))))
315 (defmeth regression-model-proto
:sweep-matrix
()
318 Returns the swept sweep matrix. For internal use"
319 (if (send self
:needs-computing
)
320 (send self
:compute
))
321 (slot-value 'sweep-matrix
))
323 (defmeth regression-model-proto
:included
(&optional new-included
)
324 "Message args: (&optional new-included)
326 With no argument, NIL means a case is not used in calculating
327 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
328 of length of y of nil and t to select cases. Estimates are
330 (when (and new-included
331 (= (length new-included
) (send self
:num-cases
)))
332 (setf (slot-value 'included
) (copy-seq new-included
))
333 (send self
:needs-computing t
))
334 (if (slot-value 'included
)
335 (slot-value 'included
)
336 (repeat t
(send self
:num-cases
))))
338 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
339 "Message args: (&optional (names nil set))
341 With no argument returns the predictor names. NAMES sets the names."
342 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
343 (let ((p (array-dimension (send self
:x
) 1))
344 (p-names (slot-value 'predictor-names
)))
345 (if (not (and p-names
(= (length p-names
) p
)))
346 (setf (slot-value 'predictor-names
)
347 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
349 (slot-value 'predictor-names
))
351 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
352 "Message args: (&optional name)
354 With no argument returns the response name. NAME sets the name."
356 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
357 (slot-value 'response-name
))
359 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
360 "Message args: (&optional labels)
361 With no argument returns the case-labels. LABELS sets the labels."
362 (if set
(setf (slot-value 'case-labels
)
364 (mapcar #'string labels
)
365 (mapcar #'(lambda (x) (format nil
"~d" x
))
366 (iseq 0 (- (send self
:num-cases
) 1))))))
367 (slot-value 'case-labels
))
371 ;;; None of these methods access any slots directly.
374 (defmeth regression-model-proto
:num-cases
()
376 Returns the number of cases in the model."
377 (length (send self
:y
)))
379 (defmeth regression-model-proto
:num-included
()
381 Returns the number of cases used in the computations."
382 (sum (if-else (send self
:included
) 1 0)))
384 (defmeth regression-model-proto
:num-coefs
()
386 Returns the number of coefficients in the fit model (including the
387 intercept if the model includes one)."
388 (if (send self
:intercept
)
389 (+ 1 (length (send self
:basis
)))
390 (length (send self
:basis
))))
392 (defmeth regression-model-proto
:df
()
394 Returns the number of degrees of freedom in the model."
395 (- (send self
:num-included
) (send self
:num-coefs
)))
397 (defmeth regression-model-proto
:x-matrix
()
399 Returns the X matrix for the model, including a column of 1's, if
400 appropriate. Columns of X matrix correspond to entries in basis."
401 (let ((m (select (send self
:x
)
402 (iseq 0 (- (send self
:num-cases
) 1))
403 (send self
:basis
))))
404 (if (send self
:intercept
)
405 (bind-columns (repeat 1 (send self
:num-cases
)) m
)
408 (defmeth regression-model-proto
:leverages
()
410 Returns the diagonal elements of the hat matrix."
411 (let* ((weights (send self
:weights
))
412 (x (send self
:x-matrix
))
414 (matmult (* (matmult x
(send self
:xtxinv
)) x
)
415 (repeat 1 (send self
:num-coefs
)))))
416 (if weights
(* weights raw-levs
) raw-levs
)))
418 (defmeth regression-model-proto
:fit-values
()
420 Returns the fitted values for the model."
421 (matmult (send self
:x-matrix
) (send self
:coef-estimates
)))
423 (defmeth regression-model-proto
:raw-residuals
()
425 Returns the raw residuals for a model."
426 (- (send self
:y
) (send self
:fit-values
)))
428 (defmeth regression-model-proto
:residuals
()
430 Returns the raw residuals for a model without weights. If the model
431 includes weights the raw residuals times the square roots of the weights
433 (let ((raw-residuals (send self
:raw-residuals
))
434 (weights (send self
:weights
)))
435 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
437 (defmeth regression-model-proto
:sum-of-squares
()
439 Returns the error sum of squares for the model."
440 (send self
:residual-sum-of-squares
))
442 (defmeth regression-model-proto
:sigma-hat
()
444 Returns the estimated standard deviation of the deviations about the
446 (let ((ss (send self
:sum-of-squares
))
447 (df (send self
:df
)))
448 (if (/= df
0) (sqrt (/ ss df
)))))
450 ;; for models without an intercept the 'usual' formula for R^2 can give
451 ;; negative results; hence the max.
452 (defmeth regression-model-proto
:r-squared
()
454 Returns the sample squared multiple correlation coefficient, R squared, for
456 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
459 (defmeth regression-model-proto
:coef-estimates
()
462 Returns the OLS (ordinary least squares) estimates of the regression
463 coefficients. Entries beyond the intercept correspond to entries in
465 (let ((n (array-dimension (send self
:x
) 1))
466 (indices (flatten-list
467 (if (send self
:intercept
)
468 (cons 0 (+ 1 (send self
:basis
)))
469 (list (+ 1 (send self
:basis
))))))
470 (m (send self
:sweep-matrix
)))
471 (format t
"~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
472 m n indices
(send self
:basis
))
473 (coerce (compound-data-seq (select m
(+ 1 n
) indices
)) 'list
))) ;; ERROR
475 (defmeth regression-model-proto
:xtxinv
()
477 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
478 (let ((indices (if (send self
:intercept
)
479 (cons 0 (1+ (send self
:basis
)))
480 (1+ (send self
:basis
)))))
481 (select (send self
:sweep-matrix
) indices indices
)))
483 (defmeth regression-model-proto
:coef-standard-errors
()
485 Returns estimated standard errors of coefficients. Entries beyond the
486 intercept correspond to entries in basis."
487 (let ((s (send self
:sigma-hat
)))
488 (if s
(* (send self
:sigma-hat
) (sqrt (diagonal (send self
:xtxinv
)))))))
490 (defmeth regression-model-proto
:studentized-residuals
()
492 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
493 (let ((res (send self
:residuals
))
494 (lev (send self
:leverages
))
495 (sig (send self
:sigma-hat
))
496 (inc (send self
:included
)))
498 (/ res
(* sig
(sqrt (pmax .00001 (- 1 lev
)))))
499 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
501 (defmeth regression-model-proto
:externally-studentized-residuals
()
503 Computes the externally studentized residuals."
504 (let* ((res (send self
:studentized-residuals
))
505 (df (send self
:df
)))
506 (if-else (send self
:included
)
507 (* res
(sqrt (/ (- df
1) (- df
(^ res
2)))))
510 (defmeth regression-model-proto
:cooks-distances
()
512 Computes Cook's distances."
513 (let ((lev (send self
:leverages
))
514 (res (/ (^
(send self
:studentized-residuals
) 2)
515 (send self
:num-coefs
))))
516 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
519 (defun plot-points (x y
&rest args
)
521 (declare (ignore x y args
))
522 (error "Graphics not implemented yet."))
524 ;; Can not plot points yet!!
525 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
526 "Message args: (&optional x-values)
527 Opens a window with a plot of the residuals. If X-VALUES are not supplied
528 the fitted values are used. The plot can be linked to other plots with the
529 link-views function. Returns a plot object."
530 (plot-points (if x-values x-values
(send self
:fit-values
))
531 (send self
:residuals
)
532 :title
"Residual Plot"
533 :point-labels
(send self
:case-labels
)))
535 (defmeth regression-model-proto
:plot-bayes-residuals
537 "Message args: (&optional x-values)
539 Opens a window with a plot of the standardized residuals and two
540 standard error bars for the posterior distribution of the actual
541 deviations from the line. See Chaloner and Brant. If X-VALUES are not
542 supplied the fitted values are used. The plot can be linked to other
543 plots with the link-views function. Returns a plot object."
545 (let* ((r (/ (send self
:residuals
)
546 (send self
:sigma-hat
)))
547 (d (* 2 (sqrt (send self
:leverages
))))
550 (x-values (if x-values x-values
(send self
:fit-values
)))
551 (p (plot-points x-values r
552 :title
"Bayes Residual Plot"
553 :point-labels
(send self
:case-labels
))))
554 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
555 x-values low x-values high
)
556 (send p
:adjust-to-data
)