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")
55 ;; might add args: (method 'gelsy), or do we want to put a more
56 ;; general front end, linear-least-square, across the range of
58 (defun lm (x y
&optional rcond
(intercept T
))
59 "fit the linear model:
62 and estimate \beta. X,Y should be in cases-by-vars form, i.e. X
63 should be n x p, Y should be n x 1. Returns estimates, n and p.
64 Probably should return a form providing the call, as well.
66 R's lm object returns: coefficients, residuals, effects, rank, fitted,
67 qr-results for numerical considerations, DF_resid. Need to
68 encapsulate into a class or struct."
69 (check-type x matrix-like
)
70 (check-type y vector-like
) ; vector-like might be too strict?
72 (assert (= (nrows y
) (nrows x
)) ; same number of observations/cases
73 (x y
) "Can not multiply x:~S by y:~S" x y
)
74 (let ((x1 (if intercept
75 (bind2 (ones (matrix-dimension x
0) 1)
78 (let ((betahat (gelsy (m* (transpose x1
) x1
)
81 (coerce (expt 2 -
52) 'double-float
)
87 (* (coerce (expt 2 -
52) 'double-float
)
90 ;; need computation for SEs,
92 (list betahat
; LA-SIMPLE-VECTOR-DOUBLE
93 betahat1
; LA-SLICE-VECVIEW-DOUBLE
94 (xtxinv x1
); (sebetahat betahat x y) ; TODO: write me!
95 (nrows x
) ; surrogate for n
96 (ncols x1
) ; surrogate for p
97 (v- (first betahat
) (first betahat1
))))))
102 (defun regression-model
107 (included (repeat t
(vector-dimension y
)))
111 (doc "Undocumented Regression Model Instance")
113 "Args: (x y &key (intercept T) (print T) (weights nil)
114 included predictor-names response-name case-labels)
115 X - list of independent variables or X matrix
116 Y - dependent variable.
117 INTERCEPT - T to include (default), NIL for no intercept
118 PRINT - if not NIL print summary information
119 WEIGHTS - if supplied should be the same length as Y; error
121 assumed to be inversely proportional to WEIGHTS
122 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
123 - sequences of strings or symbols.
124 INCLUDED - if supplied should be the same length as Y, with
125 elements nil to skip a in computing estimates (but not
126 in residual analysis).
127 Returns a regression model object. To examine the model further assign the
128 result to a variable and send it messages.
129 Example (data are in file absorbtion.lsp in the sample data directory):
130 (def m (regression-model (list iron aluminum) absorbtion))
131 (send m :help) (send m :plot-residuals)"
133 ((typep x
'matrix-like
) x
)
134 #| assume only numerical vectors -- but we need to ensure coercion to float.
135 ((or (typep x
'sequence
)
138 (make-vector (length x
) :initial-contents x
)))
140 (t (error "not matrix-like.");x
141 ))) ;; actually, might should barf.
143 ((typep y
'vector-like
) y
)
146 (numberp (car x
))) (make-vector (length y
) :initial-contents y
))
148 (t (error "not vector-like."); y
149 ))) ;; actually, might should barf.
150 (m (send regression-model-proto
:new
)))
155 (send m
:intercept intercept
)
156 (send m
:weights weights
)
157 (send m
:included included
)
158 (send m
:predictor-names predictor-names
)
159 (send m
:response-name response-name
)
160 (send m
:case-labels case-labels
)
164 (format t
"~S~%" (send m
:doc
))
165 (format t
"X: ~S~%" (send m
:x
))
166 (format t
"Y: ~S~%" (send m
:y
))))
167 (if print
(send m
:display
))
173 (defmeth regression-model-proto
:isnew
()
174 (send self
:needs-computing t
))
176 (defmeth regression-model-proto
:save
()
178 Returns an expression that will reconstruct the regression model."
179 `(regression-model ',(send self
:x
)
181 :intercept
',(send self
:intercept
)
182 :weights
',(send self
:weights
)
183 :included
',(send self
:included
)
184 :predictor-names
',(send self
:predictor-names
)
185 :response-name
',(send self
:response-name
)
186 :case-labels
',(send self
:case-labels
)))
188 ;;; Computing and Display Methods
193 ;; so with (= (dim X) (list n p))
194 ;; we end up with p x p p x 1
197 ;; and this can be implemented by
199 (setf XY
(bind2 X Y
:by
:row
))
200 (setf XYtXY
(m* (transpose XY
) XY
))
202 ;; which is too procedural. Sigh, I meant
204 (setf XYtXY
(let ((XY (bind2 X Y
:by
:row
)))
205 (m* (transpose XY
) XY
)))
207 ;; which at least looks lispy.
209 (defmeth regression-model-proto
:compute
()
211 Recomputes the estimates. For internal use by other messages"
212 (let* ((included (if-else (send self
:included
) 1d0
0d0
))
215 (intercept (send self
:intercept
)) ;; T/nil
216 (weights (send self
:weights
)) ;; vector-like or nil
217 (w (if weights
(* included weights
) included
))
218 (m (make-sweep-matrix x y w
)) ;;; ERROR HERE of course!
219 (n (matrix-dimension x
1))
221 (1- (matrix-dimension m
0))
222 (matrix-dimension m
0))) ;; remove intercept from # params -- right?
223 (tss ) ; recompute, since we aren't sweeping...
225 (reduce #'* (mapcar #'standard-deviation
226 (list-of-columns x
))))))
228 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
229 sweep-result x y m tss
)
231 (send self
:beta-coefficents
(lm x y
))
232 (send self
:xtxinv
(xtxinv x
)) ;; could extract from (lm ...)
234 (setf (slot-value 'sweep-matrix
) (first sweep-result
))
235 (setf (slot-value 'total-sum-of-squares
) tss
)
236 (setf (slot-value 'residual-sum-of-squares
)
237 (mref (first sweep-result
) p p
))
238 ;; SOMETHING WRONG HERE! FIX-ME
239 (setf (slot-value 'basis
)
240 (let ((b (remove 0 (second sweep-result
))))
241 (if b
(- (reduce #'-
(reverse b
)) 1)
242 (error "no columns could be swept"))))))
244 (defmeth regression-model-proto
:needs-computing
(&optional set
)
245 "Message args: ( &optional set )
247 If value given, sets the flag for whether (re)computation is needed to
248 update the model fits."
250 (if set
(setf (slot-value 'sweep-matrix
) nil
))
251 (null (slot-value 'sweep-matrix
)))
253 (defmeth regression-model-proto
:display
()
256 Prints the least squares regression summary. Variables not used in the fit
257 are marked as aliased."
258 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
259 (se-s (send self
:coef-standard-errors
))
261 (p-names (send self
:predictor-names
)))
262 (if (send self
:weights
)
263 (format t
"~%Weighted Least Squares Estimates:~2%")
264 (format t
"~%Least Squares Estimates:~2%"))
265 (when (send self
:intercept
)
266 (format t
"Constant ~10f ~A~%"
267 (car coefs
) (list (car se-s
)))
268 (setf coefs
(cdr coefs
))
269 (setf se-s
(cdr se-s
)))
270 (dotimes (i (array-dimension x
1))
272 ((member i
(send self
:basis
))
273 (format t
"~22a ~10f ~A~%"
274 (select p-names i
) (car coefs
) (list (car se-s
)))
275 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
276 (t (format t
"~22a aliased~%" (select p-names i
)))))
278 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
279 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
280 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
281 (if (/= (send self
:num-cases
) (send self
:num-included
))
282 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
283 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
286 ;;; Slot accessors and mutators
288 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
289 "Message args: (&optional new-doc)
291 Returns the DOC-STRING as supplied to m.
292 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
293 NEW-DOC. In this setting, when APPEND is T, don't replace and just
294 append NEW-DOC to DOC."
296 (when (and new-doc
(stringp new-doc
))
297 (setf (slot-value 'doc
)
306 (defmeth regression-model-proto
:x
(&optional new-x
)
307 "Message args: (&optional new-x)
309 With no argument returns the x matrix-like as supplied to m. With an
310 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
312 (when (and new-x
(typep new-x
'matrix-like
))
313 (setf (slot-value 'x
) new-x
)
314 (send self
:needs-computing t
))
317 (defmeth regression-model-proto
:y
(&optional new-y
)
318 "Message args: (&optional new-y)
320 With no argument returns the y vector-like as supplied to m. With an
321 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
324 (typep new-y
'vector-like
))
325 (setf (slot-value 'y
) new-y
) ;; fixme -- pls set slot value to a vector-like!
326 (send self
:needs-computing t
))
329 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
330 "Message args: (&optional new-intercept)
332 With no argument returns T if the model includes an intercept term,
333 nil if not. With an argument NEW-INTERCEPT the model is changed to
334 include or exclude an intercept, according to the value of
337 (setf (slot-value 'intercept
) val
)
338 (send self
:needs-computing t
))
339 (slot-value 'intercept
))
341 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
342 "Message args: (&optional new-w)
344 With no argument returns the weight vector-like as supplied to m; NIL
345 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
346 and recomputes the estimates."
348 #|
;; probably need to use "check-type" or similar?
351 (typep new-w
'vector-like
)))
353 (setf (slot-value 'weights
) new-w
)
354 (send self
:needs-computing t
))
355 (slot-value 'weights
))
357 (defmeth regression-model-proto
:total-sum-of-squares
()
360 Returns the total sum of squares around the mean.
361 This is recomputed if an update is needed."
362 (if (send self
:needs-computing
)
363 (send self
:compute
))
364 (slot-value 'total-sum-of-squares
))
366 (defmeth regression-model-proto
:residual-sum-of-squares
()
369 Returns the residual sum of squares for the model.
370 This is recomputed if an update is needed."
371 (if (send self
:needs-computing
)
372 (send self
:compute
))
373 (slot-value 'residual-sum-of-squares
))
375 (defmeth regression-model-proto
:basis
()
378 Returns the indices of the variables used in fitting the model, in a
380 This is recomputed if an update is needed."
381 (if (send self
:needs-computing
)
382 (send self
:compute
))
385 (defmeth regression-model-proto
:included
(&optional new-included
)
386 "Message args: (&optional new-included)
388 With no argument, NIL means a case is not used in calculating
389 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
390 of length of y of nil and t to select cases. Estimates are
395 (= (length new-included
) (send self
:num-cases
)))
397 (setf (slot-value 'included
) (copy-seq new-included
))
398 (send self
:needs-computing t
))
399 (if (slot-value 'included
)
400 (slot-value 'included
)
401 (repeat t
(send self
:num-cases
))))
403 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
404 "Message args: (&optional (names nil set))
406 With no argument returns the predictor names. NAMES sets the names."
407 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
408 (let ((p (matrix-dimension (send self
:x
) 1))
409 (p-names (slot-value 'predictor-names
)))
410 (if (not (and p-names
(= (length p-names
) p
)))
411 (setf (slot-value 'predictor-names
)
412 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
414 (slot-value 'predictor-names
))
416 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
417 "Message args: (&optional name)
419 With no argument returns the response name. NAME sets the name."
421 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
422 (slot-value 'response-name
))
424 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
425 "Message args: (&optional labels)
426 With no argument returns the case-labels. LABELS sets the labels."
427 (if set
(setf (slot-value 'case-labels
)
429 (mapcar #'string labels
)
430 (mapcar #'(lambda (x) (format nil
"~d" x
))
431 (iseq 0 (- (send self
:num-cases
) 1))))))
432 (slot-value 'case-labels
))
436 ;;; None of these methods access any slots directly.
439 (defmeth regression-model-proto
:num-cases
()
441 Returns the number of cases in the model."
442 (nelts (send self
:y
)))
444 (defmeth regression-model-proto
:num-included
()
446 Returns the number of cases used in the computations."
447 (sum (if-else (send self
:included
) 1 0)))
449 (defmeth regression-model-proto
:num-coefs
()
451 Returns the number of coefficients in the fit model (including the
452 intercept if the model includes one)."
453 (if (send self
:intercept
)
454 (+ 1 (nelts (send self
:basis
)))
455 (nelts (send self
:basis
))))
457 (defmeth regression-model-proto
:df
()
459 Returns the number of degrees of freedom in the model."
460 (- (send self
:num-included
) (send self
:num-coefs
)))
462 (defmeth regression-model-proto
:x-matrix
()
464 Returns the X matrix for the model, including a column of 1's, if
465 appropriate. Columns of X matrix correspond to entries in basis."
466 (let ((m (select (send self
:x
)
467 (iseq 0 (- (send self
:num-cases
) 1))
468 (send self
:basis
))))
469 (if (send self
:intercept
)
470 (bind2 (repeat 1 (send self
:num-cases
)) m
)
473 (defmeth regression-model-proto
:leverages
()
475 Returns the diagonal elements of the hat matrix."
476 (let* ((weights (send self
:weights
))
477 (x (send self
:x-matrix
))
479 (m* (* (m* x
(send self
:xtxinv
)) x
)
480 (repeat 1 (send self
:num-coefs
)))))
481 (if weights
(* weights raw-levs
) raw-levs
)))
483 (defmeth regression-model-proto
:fit-values
()
485 Returns the fitted values for the model."
486 (m* (send self
:x-matrix
) (send self
:coef-estimates
)))
488 (defmeth regression-model-proto
:raw-residuals
()
490 Returns the raw residuals for a model."
491 (- (send self
:y
) (send self
:fit-values
)))
493 (defmeth regression-model-proto
:residuals
()
495 Returns the raw residuals for a model without weights. If the model
496 includes weights the raw residuals times the square roots of the weights
498 (let ((raw-residuals (send self
:raw-residuals
))
499 (weights (send self
:weights
)))
500 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
502 (defmeth regression-model-proto
:sum-of-squares
()
504 Returns the error sum of squares for the model."
505 (send self
:residual-sum-of-squares
))
507 (defmeth regression-model-proto
:sigma-hat
()
509 Returns the estimated standard deviation of the deviations about the
511 (let ((ss (send self
:sum-of-squares
))
512 (df (send self
:df
)))
513 (if (/= df
0) (sqrt (/ ss df
)))))
515 ;; for models without an intercept the 'usual' formula for R^2 can give
516 ;; negative results; hence the max.
517 (defmeth regression-model-proto
:r-squared
()
519 Returns the sample squared multiple correlation coefficient, R squared, for
521 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
524 (defmeth regression-model-proto
:coef-estimates
()
527 Returns the OLS (ordinary least squares) estimates of the regression
528 coefficients. Entries beyond the intercept correspond to entries in
530 (let ((n (matrix-dimension (send self
:x
) 1))
531 (indices (flatten-list
532 (if (send self
:intercept
)
533 (cons 0 (+ 1 (send self
:basis
)))
534 (list (+ 1 (send self
:basis
))))))
535 (m (send self
:sweep-matrix
)))
536 (format t
"~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
537 m n indices
(send self
:basis
))
538 (coerce (compound-data-seq (select m
(1+ n
) indices
)) 'list
))) ;; ERROR
540 (defmeth regression-model-proto
:xtxinv
()
542 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
543 (let ((indices (if (send self
:intercept
)
544 (cons 0 (1+ (send self
:basis
)))
545 (1+ (send self
:basis
)))))
546 (select (send self
:sweep-matrix
) indices indices
)))
548 (defmeth regression-model-proto
:coef-standard-errors
()
550 Returns estimated standard errors of coefficients. Entries beyond the
551 intercept correspond to entries in basis."
552 (let ((s (send self
:sigma-hat
)))
553 (if s
(* (send self
:sigma-hat
) (sqrt (diagonalf (send self
:xtxinv
)))))))
555 (defmeth regression-model-proto
:studentized-residuals
()
557 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
558 (let ((res (send self
:residuals
))
559 (lev (send self
:leverages
))
560 (sig (send self
:sigma-hat
))
561 (inc (send self
:included
)))
563 (/ res
(* sig
(sqrt (max .00001 (- 1 lev
))))) ; vectorize max
564 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
566 (defmeth regression-model-proto
:externally-studentized-residuals
()
568 Computes the externally studentized residuals."
569 (let* ((res (send self
:studentized-residuals
))
570 (df (send self
:df
)))
571 (if-else (send self
:included
)
572 (* res
(sqrt (/ (- df
1) (- df
(^ res
2)))))
575 (defmeth regression-model-proto
:cooks-distances
()
577 Computes Cook's distances."
578 (let ((lev (send self
:leverages
))
579 (res (/ (^
(send self
:studentized-residuals
) 2)
580 (send self
:num-coefs
))))
581 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
584 (defun plot-points (x y
&rest args
)
586 (declare (ignore x y args
))
587 (error "Graphics not implemented yet."))
589 ;; Can not plot points yet!!
590 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
591 "Message args: (&optional x-values)
592 Opens a window with a plot of the residuals. If X-VALUES are not supplied
593 the fitted values are used. The plot can be linked to other plots with the
594 link-views function. Returns a plot object."
595 (plot-points (if x-values x-values
(send self
:fit-values
))
596 (send self
:residuals
)
597 :title
"Residual Plot"
598 :point-labels
(send self
:case-labels
)))
600 (defmeth regression-model-proto
:plot-bayes-residuals
602 "Message args: (&optional x-values)
604 Opens a window with a plot of the standardized residuals and two
605 standard error bars for the posterior distribution of the actual
606 deviations from the line. See Chaloner and Brant. If X-VALUES are not
607 supplied the fitted values are used. The plot can be linked to other
608 plots with the link-views function. Returns a plot object."
610 (let* ((r (/ (send self
:residuals
)
611 (send self
:sigma-hat
)))
612 (d (* 2 (sqrt (send self
:leverages
))))
615 (x-values (if x-values x-values
(send self
:fit-values
)))
616 (p (plot-points x-values r
617 :title
"Bayes Residual Plot"
618 :point-labels
(send self
:case-labels
))))
619 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
620 x-values low x-values high
)
621 (send p
:adjust-to-data
)