3 ;;; Copyright (c) 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.
17 ;;; This version uses lisp-matrix for underlying numerics.
19 (in-package :lisp-stat-regression-linear
)
21 ;;; Regresion Model Prototype
23 ;; The general strategy behind the fitting of models using prototypes
24 ;; is that we need to think about want the actual fits are, and then
25 ;; the fits can be used to recompute as components are changes. One
26 ;; catch here is that we'd like some notion of trace-ability, in
27 ;; particular, there is not necessarily a fixed way to take care of the
28 ;; audit trail. save-and-die might be a means of recording the final
29 ;; approach, but we are challenged by the problem of using advice and
30 ;; other such features to capture stages and steps that are considered
31 ;; along the goals of estimating a model.
33 ;; Note that the above is a stream-of-conscience response to the
34 ;; challenge of reproducibility in the setting of prototype "on-line"
37 (defvar regression-model-proto nil
38 "Prototype for all regression model instances.")
40 (defproto regression-model-proto
41 '(x y intercept sweep-matrix basis weights
44 residual-sum-of-squares
51 "Normal Linear Regression Model")
54 (defun regression-model
59 (included (repeat t
(length y
)))
63 (doc "Undocumented Regression Model Instance")
65 "Args: (x y &key (intercept T) (print T) (weights nil)
66 included predictor-names response-name case-labels)
67 X - list of independent variables or X matrix
68 Y - dependent variable.
69 INTERCEPT - T to include (default), NIL for no intercept
70 PRINT - if not NIL print summary information
71 WEIGHTS - if supplied should be the same length as Y; error
73 assumed to be inversely proportional to WEIGHTS
74 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
75 - sequences of strings or symbols.
76 INCLUDED - if supplied should be the same length as Y, with
77 elements nil to skip a in computing estimates (but not
78 in residual analysis).
79 Returns a regression model object. To examine the model further assign the
80 result to a variable and send it messages.
81 Example (data are in file absorbtion.lsp in the sample data directory):
82 (def m (regression-model (list iron aluminum) absorbtion))
83 (send m :help) (send m :plot-residuals)"
85 ((typep x
'matrix-like
) x
)
86 ((or (typep x
'vector
)
88 (numberp (car x
))) (make-vector (length x
) :initial-contents x
)))
89 (t x
))) ;; actually, might should barf.
91 ((typep y
'vector-like
) y
)
93 (numberp (car x
))) (make-vector (length y
) :initial-contents y
))
94 (t y
))) ;; actually, might should barf.
95 (m (send regression-model-proto
:new
)))
100 (send m
:intercept intercept
)
101 (send m
:weights weights
)
102 (send m
:included included
)
103 (send m
:predictor-names predictor-names
)
104 (send m
:response-name response-name
)
105 (send m
:case-labels case-labels
)
109 (format t
"~S~%" (send m
:doc
))
110 (format t
"X: ~S~%" (send m
:x
))
111 (format t
"Y: ~S~%" (send m
:y
))))
112 (if print
(send m
:display
))
116 ;; regression-model is the old API, but regression as a generic will
117 ;; be the new API. We need to distinguish between APIs which enable
118 ;; the user to do clear activities, and APIs which enable developers
119 ;; to do clear extensions and development, and underlying
120 ;; infrastructure to keep everything straight and enabled.
126 (defgeneric regression
;; assumes x/y from lisp-matrix -- start of a set of generics.
128 "Args: (x y &key (intercept T) (print T) (weights nil)
129 included predictor-names response-name case-labels)
130 X - list of independent variables or X matrix
131 Y - dependent variable.
132 INTERCEPT - T to include (default), NIL for no intercept
133 PRINT - if not NIL print summary information
134 WEIGHTS - if supplied should be the same length as Y; error
136 assumed to be inversely proportional to WEIGHTS
137 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
138 - sequences of strings or symbols.
139 INCLUDED - if supplied should be the same length as Y, with
140 elements nil to skip a in computing estimates (but not
141 in residual analysis).
142 Returns a regression model object. To examine the model further assign the
143 result to a variable and send it messages.
144 Example (data are in file absorbtion.lsp in the sample data directory):
145 (def m (regression-model (list iron aluminum) absorbtion))
146 (send m :help) (send m :plot-residuals)"
147 (let ((m (send regression-model-proto
:new
)))
152 (send m
:intercept intercept
)
153 (send m
:weights weights
)
154 (send m
:included included
)
155 (send m
:predictor-names predictor-names
)
156 (send m
:response-name response-name
)
157 (send m
:case-labels case-labels
)
161 (format t
"~S~%" (send m
:doc
))
162 (format t
"X: ~S~%" (send m
:x
))
163 (format t
"Y: ~S~%" (send m
:y
))))
164 (if print
(send m
:display
))
169 (defmeth regression-model-proto
:isnew
()
170 (send self
:needs-computing t
))
172 (defmeth regression-model-proto
:save
()
174 Returns an expression that will reconstruct the regression model."
175 `(regression-model ',(send self
:x
)
177 :intercept
',(send self
:intercept
)
178 :weights
',(send self
:weights
)
179 :included
',(send self
:included
)
180 :predictor-names
',(send self
:predictor-names
)
181 :response-name
',(send self
:response-name
)
182 :case-labels
',(send self
:case-labels
)))
184 ;;; Computing and Display Methods
186 (defmeth regression-model-proto
:compute
()
188 Recomputes the estimates. For internal use by other messages"
189 (let* ((included (if-else (send self
:included
) 1 0))
192 (intercept (send self
:intercept
))
193 (weights (send self
:weights
))
194 (w (if weights
(* included weights
) included
))
195 (m (make-sweep-matrix x y w
)) ;;; ERROR HERE
196 (n (matrix-dimension x
1))
197 (p (- (matrix-dimension m
0) 1))
200 (reduce #'* (mapcar #'standard-deviation
(list-of-columns x
)))))
203 (sweep-operator m
(iseq 1 n
) tol
)
204 (sweep-operator m
(iseq 0 n
) (cons 0.0 tol
)))))
206 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
207 sweep-result x y m tss
)
208 (setf (slot-value 'sweep-matrix
) (first sweep-result
))
209 (setf (slot-value 'total-sum-of-squares
) tss
)
210 (setf (slot-value 'residual-sum-of-squares
)
211 (mref (first sweep-result
) p p
))
212 ;; SOMETHING WRONG HERE! FIX-ME
213 (setf (slot-value 'basis
)
214 (let ((b (remove 0 (second sweep-result
))))
215 (if b
(- (reduce #'-
(reverse b
)) 1)
216 (error "no columns could be swept"))))))
218 (defmeth regression-model-proto
:needs-computing
(&optional set
)
219 "Message args: ( &optional set )
221 If value given, sets the flag for whether (re)computation is needed to
222 update the model fits."
224 (if set
(setf (slot-value 'sweep-matrix
) nil
))
225 (null (slot-value 'sweep-matrix
)))
227 (defmeth regression-model-proto
:display
()
230 Prints the least squares regression summary. Variables not used in the fit
231 are marked as aliased."
232 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
233 (se-s (send self
:coef-standard-errors
))
235 (p-names (send self
:predictor-names
)))
236 (if (send self
:weights
)
237 (format t
"~%Weighted Least Squares Estimates:~2%")
238 (format t
"~%Least Squares Estimates:~2%"))
239 (when (send self
:intercept
)
240 (format t
"Constant ~10f ~A~%"
241 (car coefs
) (list (car se-s
)))
242 (setf coefs
(cdr coefs
))
243 (setf se-s
(cdr se-s
)))
244 (dotimes (i (array-dimension x
1))
246 ((member i
(send self
:basis
))
247 (format t
"~22a ~10f ~A~%"
248 (select p-names i
) (car coefs
) (list (car se-s
)))
249 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
250 (t (format t
"~22a aliased~%" (select p-names i
)))))
252 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
253 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
254 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
255 (if (/= (send self
:num-cases
) (send self
:num-included
))
256 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
257 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
260 ;;; Slot accessors and mutators
262 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
263 "Message args: (&optional new-doc)
265 Returns the DOC-STRING as supplied to m.
266 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
267 NEW-DOC. In this setting, when APPEND is T, append NEW-DOC to DOC
268 rather than doing replacement."
270 (when (and new-doc
(stringp new-doc
))
271 (setf (slot-value 'doc
)
280 (defmeth regression-model-proto
:x
(&optional new-x
)
281 "Message args: (&optional new-x)
283 With no argument returns the x matrix-like as supplied to m. With an
284 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
286 (when (and new-x
(typep new-x
'matrix-like
))
287 (setf (slot-value 'x
) new-x
)
288 (send self
:needs-computing t
))
291 (defmeth regression-model-proto
:y
(&optional new-y
)
292 "Message args: (&optional new-y)
294 With no argument returns the y vector-like as supplied to m. With an
295 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
298 (typep new-y
'vector-like
))
299 (setf (slot-value 'y
) new-y
) ;; fixme -- pls set slot value to a vector-like!
300 (send self
:needs-computing t
))
303 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
304 "Message args: (&optional new-intercept)
306 With no argument returns T if the model includes an intercept term,
307 nil if not. With an argument NEW-INTERCEPT the model is changed to
308 include or exclude an intercept, according to the value of
311 (setf (slot-value 'intercept
) val
)
312 (send self
:needs-computing t
))
313 (slot-value 'intercept
))
315 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
316 "Message args: (&optional new-w)
318 With no argument returns the weight vector-like as supplied to m; NIL
319 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
320 and recomputes the estimates."
322 (typep new-w
'vector-like
))
323 (setf (slot-value 'weights
) new-w
)
324 (send self
:needs-computing t
))
325 (slot-value 'weights
))
327 (defmeth regression-model-proto
:total-sum-of-squares
()
330 Returns the total sum of squares around the mean.
331 This is recomputed if an update is needed."
332 (if (send self
:needs-computing
)
333 (send self
:compute
))
334 (slot-value 'total-sum-of-squares
))
336 (defmeth regression-model-proto
:residual-sum-of-squares
()
339 Returns the residual sum of squares for the model.
340 This is recomputed if an update is needed."
341 (if (send self
:needs-computing
)
342 (send self
:compute
))
343 (slot-value 'residual-sum-of-squares
))
345 (defmeth regression-model-proto
:basis
()
348 Returns the indices of the variables used in fitting the model, in a
350 This is recomputed if an update is needed."
351 (if (send self
:needs-computing
)
352 (send self
:compute
))
356 (defmeth regression-model-proto
:sweep-matrix
()
359 Returns the swept sweep matrix. For internal use"
360 (if (send self
:needs-computing
)
361 (send self
:compute
))
362 (slot-value 'sweep-matrix
))
364 (defmeth regression-model-proto
:included
(&optional new-included
)
365 "Message args: (&optional new-included)
367 With no argument, NIL means a case is not used in calculating
368 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
369 of length of y of nil and t to select cases. Estimates are
371 (when (and new-included
372 (= (nelts new-included
) (send self
:num-cases
)))
373 (setf (slot-value 'included
) (copy-seq new-included
))
374 (send self
:needs-computing t
))
375 (if (slot-value 'included
)
376 (slot-value 'included
)
377 (repeat t
(send self
:num-cases
))))
379 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
380 "Message args: (&optional (names nil set))
382 With no argument returns the predictor names. NAMES sets the names."
383 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
384 (let ((p (matrix-dimension (send self
:x
) 1))
385 (p-names (slot-value 'predictor-names
)))
386 (if (not (and p-names
(= (length p-names
) p
)))
387 (setf (slot-value 'predictor-names
)
388 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
390 (slot-value 'predictor-names
))
392 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
393 "Message args: (&optional name)
395 With no argument returns the response name. NAME sets the name."
397 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
398 (slot-value 'response-name
))
400 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
401 "Message args: (&optional labels)
402 With no argument returns the case-labels. LABELS sets the labels."
403 (if set
(setf (slot-value 'case-labels
)
405 (mapcar #'string labels
)
406 (mapcar #'(lambda (x) (format nil
"~d" x
))
407 (iseq 0 (- (send self
:num-cases
) 1))))))
408 (slot-value 'case-labels
))
412 ;;; None of these methods access any slots directly.
415 (defmeth regression-model-proto
:num-cases
()
417 Returns the number of cases in the model."
418 (nelts (send self
:y
)))
420 (defmeth regression-model-proto
:num-included
()
422 Returns the number of cases used in the computations."
423 (sum (if-else (send self
:included
) 1 0)))
425 (defmeth regression-model-proto
:num-coefs
()
427 Returns the number of coefficients in the fit model (including the
428 intercept if the model includes one)."
429 (if (send self
:intercept
)
430 (+ 1 (nelts (send self
:basis
)))
431 (nelts (send self
:basis
))))
433 (defmeth regression-model-proto
:df
()
435 Returns the number of degrees of freedom in the model."
436 (- (send self
:num-included
) (send self
:num-coefs
)))
438 (defmeth regression-model-proto
:x-matrix
()
440 Returns the X matrix for the model, including a column of 1's, if
441 appropriate. Columns of X matrix correspond to entries in basis."
442 (let ((m (select (send self
:x
)
443 (iseq 0 (- (send self
:num-cases
) 1))
444 (send self
:basis
))))
445 (if (send self
:intercept
)
446 (bind2 (repeat 1 (send self
:num-cases
)) m
)
449 (defmeth regression-model-proto
:leverages
()
451 Returns the diagonal elements of the hat matrix."
452 (let* ((weights (send self
:weights
))
453 (x (send self
:x-matrix
))
455 (m* (* (m* x
(send self
:xtxinv
)) x
)
456 (repeat 1 (send self
:num-coefs
)))))
457 (if weights
(* weights raw-levs
) raw-levs
)))
459 (defmeth regression-model-proto
:fit-values
()
461 Returns the fitted values for the model."
462 (m* (send self
:x-matrix
) (send self
:coef-estimates
)))
464 (defmeth regression-model-proto
:raw-residuals
()
466 Returns the raw residuals for a model."
467 (- (send self
:y
) (send self
:fit-values
)))
469 (defmeth regression-model-proto
:residuals
()
471 Returns the raw residuals for a model without weights. If the model
472 includes weights the raw residuals times the square roots of the weights
474 (let ((raw-residuals (send self
:raw-residuals
))
475 (weights (send self
:weights
)))
476 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
478 (defmeth regression-model-proto
:sum-of-squares
()
480 Returns the error sum of squares for the model."
481 (send self
:residual-sum-of-squares
))
483 (defmeth regression-model-proto
:sigma-hat
()
485 Returns the estimated standard deviation of the deviations about the
487 (let ((ss (send self
:sum-of-squares
))
488 (df (send self
:df
)))
489 (if (/= df
0) (sqrt (/ ss df
)))))
491 ;; for models without an intercept the 'usual' formula for R^2 can give
492 ;; negative results; hence the max.
493 (defmeth regression-model-proto
:r-squared
()
495 Returns the sample squared multiple correlation coefficient, R squared, for
497 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
500 (defmeth regression-model-proto
:coef-estimates
()
503 Returns the OLS (ordinary least squares) estimates of the regression
504 coefficients. Entries beyond the intercept correspond to entries in
506 (let ((n (array-dimension (send self
:x
) 1))
507 (indices (flatten-list
508 (if (send self
:intercept
)
509 (cons 0 (+ 1 (send self
:basis
)))
510 (list (+ 1 (send self
:basis
))))))
511 (m (send self
:sweep-matrix
)))
512 (format t
"~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
513 m n indices
(send self
:basis
))
514 (coerce (compound-data-seq (select m
(+ 1 n
) indices
)) 'list
))) ;; ERROR
516 (defmeth regression-model-proto
:xtxinv
()
518 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
519 (let ((indices (if (send self
:intercept
)
520 (cons 0 (1+ (send self
:basis
)))
521 (1+ (send self
:basis
)))))
522 (select (send self
:sweep-matrix
) indices indices
)))
524 (defmeth regression-model-proto
:coef-standard-errors
()
526 Returns estimated standard errors of coefficients. Entries beyond the
527 intercept correspond to entries in basis."
528 (let ((s (send self
:sigma-hat
)))
529 (if s
(* (send self
:sigma-hat
) (sqrt (diagonalf (send self
:xtxinv
)))))))
531 (defmeth regression-model-proto
:studentized-residuals
()
533 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
534 (let ((res (send self
:residuals
))
535 (lev (send self
:leverages
))
536 (sig (send self
:sigma-hat
))
537 (inc (send self
:included
)))
539 (/ res
(* sig
(sqrt (pmax .00001 (- 1 lev
)))))
540 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
542 (defmeth regression-model-proto
:externally-studentized-residuals
()
544 Computes the externally studentized residuals."
545 (let* ((res (send self
:studentized-residuals
))
546 (df (send self
:df
)))
547 (if-else (send self
:included
)
548 (* res
(sqrt (/ (- df
1) (- df
(^ res
2)))))
551 (defmeth regression-model-proto
:cooks-distances
()
553 Computes Cook's distances."
554 (let ((lev (send self
:leverages
))
555 (res (/ (^
(send self
:studentized-residuals
) 2)
556 (send self
:num-coefs
))))
557 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
560 (defun plot-points (x y
&rest args
)
562 (declare (ignore x y args
))
563 (error "Graphics not implemented yet."))
565 ;; Can not plot points yet!!
566 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
567 "Message args: (&optional x-values)
568 Opens a window with a plot of the residuals. If X-VALUES are not supplied
569 the fitted values are used. The plot can be linked to other plots with the
570 link-views function. Returns a plot object."
571 (plot-points (if x-values x-values
(send self
:fit-values
))
572 (send self
:residuals
)
573 :title
"Residual Plot"
574 :point-labels
(send self
:case-labels
)))
576 (defmeth regression-model-proto
:plot-bayes-residuals
578 "Message args: (&optional x-values)
580 Opens a window with a plot of the standardized residuals and two
581 standard error bars for the posterior distribution of the actual
582 deviations from the line. See Chaloner and Brant. If X-VALUES are not
583 supplied the fitted values are used. The plot can be linked to other
584 plots with the link-views function. Returns a plot object."
586 (let* ((r (/ (send self
:residuals
)
587 (send self
:sigma-hat
)))
588 (d (* 2 (sqrt (send self
:leverages
))))
591 (x-values (if x-values x-values
(send self
:fit-values
)))
592 (p (plot-points x-values r
593 :title
"Bayes Residual Plot"
594 :point-labels
(send self
:case-labels
))))
595 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
596 x-values low x-values high
)
597 (send p
:adjust-to-data
)