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
(vector-dimension 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 #| assume only numerical vectors -- but we need to ensure coercion to float.
87 ((or (typep x
'sequence
)
90 (make-vector (length x
) :initial-contents x
)))
92 (t (error "not matrix-like.");x
93 ))) ;; actually, might should barf.
95 ((typep y
'vector-like
) y
)
98 (numberp (car x
))) (make-vector (length y
) :initial-contents y
))
100 (t (error "not vector-like."); y
101 ))) ;; actually, might should barf.
102 (m (send regression-model-proto
:new
)))
107 (send m
:intercept intercept
)
108 (send m
:weights weights
)
109 (send m
:included included
)
110 (send m
:predictor-names predictor-names
)
111 (send m
:response-name response-name
)
112 (send m
:case-labels case-labels
)
116 (format t
"~S~%" (send m
:doc
))
117 (format t
"X: ~S~%" (send m
:x
))
118 (format t
"Y: ~S~%" (send m
:y
))))
119 (if print
(send m
:display
))
125 (defmeth regression-model-proto
:isnew
()
126 (send self
:needs-computing t
))
128 (defmeth regression-model-proto
:save
()
130 Returns an expression that will reconstruct the regression model."
131 `(regression-model ',(send self
:x
)
133 :intercept
',(send self
:intercept
)
134 :weights
',(send self
:weights
)
135 :included
',(send self
:included
)
136 :predictor-names
',(send self
:predictor-names
)
137 :response-name
',(send self
:response-name
)
138 :case-labels
',(send self
:case-labels
)))
140 ;;; Computing and Display Methods
145 ;; so with (= (dim X) (list n p))
146 ;; we end up with p x p p x 1
149 ;; and this can be implemented by
151 (setf XY
(bind2 X Y
:by
:row
))
152 (setf XYtXY
(m* (transpose XY
) XY
))
154 ;; which is too procedural. Sigh, I meant
156 (setf XYtXY
(let ((XY (bind2 X Y
:by
:row
)))
157 (m* (transpose XY
) XY
)))
159 ;; which at least looks lispy.
161 (defmeth regression-model-proto
:compute
()
163 Recomputes the estimates. For internal use by other messages"
164 (let* ((included (if-else (send self
:included
) 1d0
0d0
))
167 (intercept (send self
:intercept
)) ;; T/nil
168 (weights (send self
:weights
)) ;; vector-like or nil
169 (w (if weights
(* included weights
) included
))
170 (beta (send :beta-coefficents
(lm x y
)))
171 (xtxinv (send :xtxinv
(XtXinv x
)))
172 (m (make-sweep-matrix x y w
)) ;;; ERROR HERE of course!
173 (n (matrix-dimension x
1))
175 (1- (matrix-dimension m
0))
176 (matrix-dimension m
0))) ;; remove intercept from # params -- right?
177 (tss ) ; recompute, since we aren't sweeping...
179 (reduce #'* (mapcar #'standard-deviation
180 (list-of-columns x
))))))
182 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
183 sweep-result x y m tss
)
184 (setf (slot-value 'sweep-matrix
) (first sweep-result
))
185 (setf (slot-value 'total-sum-of-squares
) tss
)
186 (setf (slot-value 'residual-sum-of-squares
)
187 (mref (first sweep-result
) p p
))
188 ;; SOMETHING WRONG HERE! FIX-ME
189 (setf (slot-value 'basis
)
190 (let ((b (remove 0 (second sweep-result
))))
191 (if b
(- (reduce #'-
(reverse b
)) 1)
192 (error "no columns could be swept"))))))
194 (defmeth regression-model-proto
:needs-computing
(&optional set
)
195 "Message args: ( &optional set )
197 If value given, sets the flag for whether (re)computation is needed to
198 update the model fits."
200 (if set
(setf (slot-value 'sweep-matrix
) nil
))
201 (null (slot-value 'sweep-matrix
)))
203 (defmeth regression-model-proto
:display
()
206 Prints the least squares regression summary. Variables not used in the fit
207 are marked as aliased."
208 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
209 (se-s (send self
:coef-standard-errors
))
211 (p-names (send self
:predictor-names
)))
212 (if (send self
:weights
)
213 (format t
"~%Weighted Least Squares Estimates:~2%")
214 (format t
"~%Least Squares Estimates:~2%"))
215 (when (send self
:intercept
)
216 (format t
"Constant ~10f ~A~%"
217 (car coefs
) (list (car se-s
)))
218 (setf coefs
(cdr coefs
))
219 (setf se-s
(cdr se-s
)))
220 (dotimes (i (array-dimension x
1))
222 ((member i
(send self
:basis
))
223 (format t
"~22a ~10f ~A~%"
224 (select p-names i
) (car coefs
) (list (car se-s
)))
225 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
226 (t (format t
"~22a aliased~%" (select p-names i
)))))
228 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
229 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
230 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
231 (if (/= (send self
:num-cases
) (send self
:num-included
))
232 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
233 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
236 ;;; Slot accessors and mutators
238 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
239 "Message args: (&optional new-doc)
241 Returns the DOC-STRING as supplied to m.
242 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
243 NEW-DOC. In this setting, when APPEND is T, don't replace and just
244 append NEW-DOC to DOC."
246 (when (and new-doc
(stringp new-doc
))
247 (setf (slot-value 'doc
)
256 (defmeth regression-model-proto
:x
(&optional new-x
)
257 "Message args: (&optional new-x)
259 With no argument returns the x matrix-like as supplied to m. With an
260 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
262 (when (and new-x
(typep new-x
'matrix-like
))
263 (setf (slot-value 'x
) new-x
)
264 (send self
:needs-computing t
))
267 (defmeth regression-model-proto
:y
(&optional new-y
)
268 "Message args: (&optional new-y)
270 With no argument returns the y vector-like as supplied to m. With an
271 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
274 (typep new-y
'vector-like
))
275 (setf (slot-value 'y
) new-y
) ;; fixme -- pls set slot value to a vector-like!
276 (send self
:needs-computing t
))
279 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
280 "Message args: (&optional new-intercept)
282 With no argument returns T if the model includes an intercept term,
283 nil if not. With an argument NEW-INTERCEPT the model is changed to
284 include or exclude an intercept, according to the value of
287 (setf (slot-value 'intercept
) val
)
288 (send self
:needs-computing t
))
289 (slot-value 'intercept
))
291 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
292 "Message args: (&optional new-w)
294 With no argument returns the weight vector-like as supplied to m; NIL
295 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
296 and recomputes the estimates."
298 #|
;; probably need to use "check-type" or similar?
301 (typep new-w
'vector-like
)))
303 (setf (slot-value 'weights
) new-w
)
304 (send self
:needs-computing t
))
305 (slot-value 'weights
))
307 (defmeth regression-model-proto
:total-sum-of-squares
()
310 Returns the total sum of squares around the mean.
311 This is recomputed if an update is needed."
312 (if (send self
:needs-computing
)
313 (send self
:compute
))
314 (slot-value 'total-sum-of-squares
))
316 (defmeth regression-model-proto
:residual-sum-of-squares
()
319 Returns the residual sum of squares for the model.
320 This is recomputed if an update is needed."
321 (if (send self
:needs-computing
)
322 (send self
:compute
))
323 (slot-value 'residual-sum-of-squares
))
325 (defmeth regression-model-proto
:basis
()
328 Returns the indices of the variables used in fitting the model, in a
330 This is recomputed if an update is needed."
331 (if (send self
:needs-computing
)
332 (send self
:compute
))
335 (defmeth regression-model-proto
:included
(&optional new-included
)
336 "Message args: (&optional new-included)
338 With no argument, NIL means a case is not used in calculating
339 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
340 of length of y of nil and t to select cases. Estimates are
345 (= (length new-included
) (send self
:num-cases
)))
347 (setf (slot-value 'included
) (copy-seq new-included
))
348 (send self
:needs-computing t
))
349 (if (slot-value 'included
)
350 (slot-value 'included
)
351 (repeat t
(send self
:num-cases
))))
353 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
354 "Message args: (&optional (names nil set))
356 With no argument returns the predictor names. NAMES sets the names."
357 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
358 (let ((p (matrix-dimension (send self
:x
) 1))
359 (p-names (slot-value 'predictor-names
)))
360 (if (not (and p-names
(= (length p-names
) p
)))
361 (setf (slot-value 'predictor-names
)
362 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
364 (slot-value 'predictor-names
))
366 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
367 "Message args: (&optional name)
369 With no argument returns the response name. NAME sets the name."
371 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
372 (slot-value 'response-name
))
374 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
375 "Message args: (&optional labels)
376 With no argument returns the case-labels. LABELS sets the labels."
377 (if set
(setf (slot-value 'case-labels
)
379 (mapcar #'string labels
)
380 (mapcar #'(lambda (x) (format nil
"~d" x
))
381 (iseq 0 (- (send self
:num-cases
) 1))))))
382 (slot-value 'case-labels
))
386 ;;; None of these methods access any slots directly.
389 (defmeth regression-model-proto
:num-cases
()
391 Returns the number of cases in the model."
392 (nelts (send self
:y
)))
394 (defmeth regression-model-proto
:num-included
()
396 Returns the number of cases used in the computations."
397 (sum (if-else (send self
:included
) 1 0)))
399 (defmeth regression-model-proto
:num-coefs
()
401 Returns the number of coefficients in the fit model (including the
402 intercept if the model includes one)."
403 (if (send self
:intercept
)
404 (+ 1 (nelts (send self
:basis
)))
405 (nelts (send self
:basis
))))
407 (defmeth regression-model-proto
:df
()
409 Returns the number of degrees of freedom in the model."
410 (- (send self
:num-included
) (send self
:num-coefs
)))
412 (defmeth regression-model-proto
:x-matrix
()
414 Returns the X matrix for the model, including a column of 1's, if
415 appropriate. Columns of X matrix correspond to entries in basis."
416 (let ((m (select (send self
:x
)
417 (iseq 0 (- (send self
:num-cases
) 1))
418 (send self
:basis
))))
419 (if (send self
:intercept
)
420 (bind2 (repeat 1 (send self
:num-cases
)) m
)
423 (defmeth regression-model-proto
:leverages
()
425 Returns the diagonal elements of the hat matrix."
426 (let* ((weights (send self
:weights
))
427 (x (send self
:x-matrix
))
429 (m* (* (m* x
(send self
:xtxinv
)) x
)
430 (repeat 1 (send self
:num-coefs
)))))
431 (if weights
(* weights raw-levs
) raw-levs
)))
433 (defmeth regression-model-proto
:fit-values
()
435 Returns the fitted values for the model."
436 (m* (send self
:x-matrix
) (send self
:coef-estimates
)))
438 (defmeth regression-model-proto
:raw-residuals
()
440 Returns the raw residuals for a model."
441 (- (send self
:y
) (send self
:fit-values
)))
443 (defmeth regression-model-proto
:residuals
()
445 Returns the raw residuals for a model without weights. If the model
446 includes weights the raw residuals times the square roots of the weights
448 (let ((raw-residuals (send self
:raw-residuals
))
449 (weights (send self
:weights
)))
450 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
452 (defmeth regression-model-proto
:sum-of-squares
()
454 Returns the error sum of squares for the model."
455 (send self
:residual-sum-of-squares
))
457 (defmeth regression-model-proto
:sigma-hat
()
459 Returns the estimated standard deviation of the deviations about the
461 (let ((ss (send self
:sum-of-squares
))
462 (df (send self
:df
)))
463 (if (/= df
0) (sqrt (/ ss df
)))))
465 ;; for models without an intercept the 'usual' formula for R^2 can give
466 ;; negative results; hence the max.
467 (defmeth regression-model-proto
:r-squared
()
469 Returns the sample squared multiple correlation coefficient, R squared, for
471 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
474 (defmeth regression-model-proto
:coef-estimates
()
477 Returns the OLS (ordinary least squares) estimates of the regression
478 coefficients. Entries beyond the intercept correspond to entries in
480 (let ((n (matrix-dimension (send self
:x
) 1))
481 (indices (flatten-list
482 (if (send self
:intercept
)
483 (cons 0 (+ 1 (send self
:basis
)))
484 (list (+ 1 (send self
:basis
))))))
485 (m (send self
:sweep-matrix
)))
486 (format t
"~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
487 m n indices
(send self
:basis
))
488 (coerce (compound-data-seq (select m
(1+ n
) indices
)) 'list
))) ;; ERROR
490 (defmeth regression-model-proto
:xtxinv
()
492 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
493 (let ((indices (if (send self
:intercept
)
494 (cons 0 (1+ (send self
:basis
)))
495 (1+ (send self
:basis
)))))
496 (select (send self
:sweep-matrix
) indices indices
)))
498 (defmeth regression-model-proto
:coef-standard-errors
()
500 Returns estimated standard errors of coefficients. Entries beyond the
501 intercept correspond to entries in basis."
502 (let ((s (send self
:sigma-hat
)))
503 (if s
(* (send self
:sigma-hat
) (sqrt (diagonalf (send self
:xtxinv
)))))))
505 (defmeth regression-model-proto
:studentized-residuals
()
507 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
508 (let ((res (send self
:residuals
))
509 (lev (send self
:leverages
))
510 (sig (send self
:sigma-hat
))
511 (inc (send self
:included
)))
513 (/ res
(* sig
(sqrt (pmax .00001 (- 1 lev
)))))
514 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
516 (defmeth regression-model-proto
:externally-studentized-residuals
()
518 Computes the externally studentized residuals."
519 (let* ((res (send self
:studentized-residuals
))
520 (df (send self
:df
)))
521 (if-else (send self
:included
)
522 (* res
(sqrt (/ (- df
1) (- df
(^ res
2)))))
525 (defmeth regression-model-proto
:cooks-distances
()
527 Computes Cook's distances."
528 (let ((lev (send self
:leverages
))
529 (res (/ (^
(send self
:studentized-residuals
) 2)
530 (send self
:num-coefs
))))
531 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
534 (defun plot-points (x y
&rest args
)
536 (declare (ignore x y args
))
537 (error "Graphics not implemented yet."))
539 ;; Can not plot points yet!!
540 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
541 "Message args: (&optional x-values)
542 Opens a window with a plot of the residuals. If X-VALUES are not supplied
543 the fitted values are used. The plot can be linked to other plots with the
544 link-views function. Returns a plot object."
545 (plot-points (if x-values x-values
(send self
:fit-values
))
546 (send self
:residuals
)
547 :title
"Residual Plot"
548 :point-labels
(send self
:case-labels
)))
550 (defmeth regression-model-proto
:plot-bayes-residuals
552 "Message args: (&optional x-values)
554 Opens a window with a plot of the standardized residuals and two
555 standard error bars for the posterior distribution of the actual
556 deviations from the line. See Chaloner and Brant. If X-VALUES are not
557 supplied the fitted values are used. The plot can be linked to other
558 plots with the link-views function. Returns a plot object."
560 (let* ((r (/ (send self
:residuals
)
561 (send self
:sigma-hat
)))
562 (d (* 2 (sqrt (send self
:leverages
))))
565 (x-values (if x-values x-values
(send self
:fit-values
)))
566 (p (plot-points x-values r
567 :title
"Bayes Residual Plot"
568 :point-labels
(send self
:case-labels
))))
569 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
570 x-values low x-values high
)
571 (send p
:adjust-to-data
)