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 betahat basis weights
44 residual-sum-of-squares
51 "Normal Linear Regression Model")
60 X is NxP, so result is PxP. Represents Var[\hat\beta], the vars for
61 \hat \beta from Y = X \beta + \eps. Done by Cholesky decomposition,
62 using LAPACK's dpotri routine to invert, after factorizing with dpotrf.
65 (let ((m1 (rand 7 5)))
68 (check-type x matrix-like
)
69 (minv-cholesky (m* (transpose x
) x
)))
72 ;; might add args: (method 'gelsy), or do we want to put a more
73 ;; general front end, linear-least-square, across the range of
75 (defun lm (x y
&optional rcond
(intercept T
))
76 "fit the linear model:
79 and estimate \beta. X,Y should be in cases-by-vars form, i.e. X
80 should be n x p, Y should be n x 1. Returns estimates, n and p.
81 Probably should return a form providing the call, as well.
83 R's lm object returns: coefficients, residuals, effects, rank, fitted,
84 qr-results for numerical considerations, DF_resid. Need to
85 encapsulate into a class or struct."
86 (check-type x matrix-like
)
87 (check-type y vector-like
) ; vector-like might be too strict?
89 (assert (= (nrows y
) (nrows x
)) ; same number of observations/cases
90 (x y
) "Can not multiply x:~S by y:~S" x y
)
91 (let ((x1 (if intercept
92 (bind2 (ones (matrix-dimension x
0) 1)
95 (let ((betahat (gelsy (m* (transpose x1
) x1
)
98 (coerce (expt 2 -
52) 'double-float
)
104 (* (coerce (expt 2 -
52) 'double-float
)
107 ;; need computation for SEs,
109 (list betahat
; LA-SIMPLE-VECTOR-DOUBLE
110 betahat1
; LA-SLICE-VECVIEW-DOUBLE
111 (xtxinv x1
); (sebetahat betahat x y) ; TODO: write me!
112 (nrows x
) ; surrogate for n
113 (ncols x1
) ; surrogate for p
114 ;; (v- (first betahat) (first betahat1))
120 (defun regression-model
125 (included (repeat t
(vector-dimension y
)))
129 (doc "Undocumented Regression Model Instance")
131 "Args: (x y &key (intercept T) (print T) (weights nil)
132 included predictor-names response-name case-labels)
133 X - list of independent variables or X matrix
134 Y - dependent variable.
135 INTERCEPT - T to include (default), NIL for no intercept
136 PRINT - if not NIL print summary information
137 WEIGHTS - if supplied should be the same length as Y; error
139 assumed to be inversely proportional to WEIGHTS
140 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
141 - sequences of strings or symbols.
142 INCLUDED - if supplied should be the same length as Y, with
143 elements nil to skip a in computing estimates (but not
144 in residual analysis).
145 Returns a regression model object. To examine the model further assign the
146 result to a variable and send it messages.
147 Example (data are in file absorbtion.lsp in the sample data directory):
148 (def m (regression-model (list iron aluminum) absorbtion))
149 (send m :help) (send m :plot-residuals)"
151 ((typep x
'matrix-like
) x
)
152 #| assume only numerical vectors -- but we need to ensure coercion to float.
153 ((or (typep x
'sequence
)
156 (make-vector (length x
) :initial-contents x
)))
158 (t (error "not matrix-like.");x
159 ))) ;; actually, might should barf.
161 ((typep y
'vector-like
) y
)
164 (numberp (car x
))) (make-vector (length y
) :initial-contents y
))
166 (t (error "not vector-like."); y
167 ))) ;; actually, might should barf.
168 (m (send regression-model-proto
:new
)))
173 (send m
:intercept intercept
)
174 (send m
:weights weights
)
175 (send m
:included included
)
176 (send m
:predictor-names predictor-names
)
177 (send m
:response-name response-name
)
178 (send m
:case-labels case-labels
)
182 (format t
"~S~%" (send m
:doc
))
183 (format t
"X: ~S~%" (send m
:x
))
184 (format t
"Y: ~S~%" (send m
:y
))))
185 (if print
(send m
:display
))
191 (defmeth regression-model-proto
:isnew
()
192 (send self
:needs-computing t
))
194 (defmeth regression-model-proto
:save
()
196 Returns an expression that will reconstruct the regression model."
197 `(regression-model ',(send self
:x
)
199 :intercept
',(send self
:intercept
)
200 :weights
',(send self
:weights
)
201 :included
',(send self
:included
)
202 :predictor-names
',(send self
:predictor-names
)
203 :response-name
',(send self
:response-name
)
204 :case-labels
',(send self
:case-labels
)))
206 ;;; Computing and Display Methods
211 ;; so with (= (dim X) (list n p))
212 ;; we end up with p x p p x 1
215 ;; and this can be implemented by
217 (setf XY
(bind2 X Y
:by
:row
))
218 (setf XYtXY
(m* (transpose XY
) XY
))
220 ;; which is too procedural. Sigh, I meant
222 (setf XYtXY
(let ((XY (bind2 X Y
:by
:row
)))
223 (m* (transpose XY
) XY
)))
225 ;; which at least looks lispy.
227 (defmeth regression-model-proto
:compute
()
229 Recomputes the estimates. For internal use by other messages"
230 (let* ((included (if-else (send self
:included
) 1d0
0d0
))
233 (intercept (send self
:intercept
)) ;; T/nil
234 (weights (send self
:weights
)) ;; vector-like or nil
235 (w (if weights
(* included weights
) included
))
236 (n (matrix-dimension x
0))
238 (1- (matrix-dimension x
1))
239 (matrix-dimension x
1))) ;; remove intercept from # params -- right?
241 (res 0 ; (compute-residuals y yhat)
244 ;; (* 0.001 (reduce #'* (mapcar #'standard-deviation (list-of-columns x))))
247 "~%REMOVEME: regr-mdl-prto :compute~%x= ~A~%y= ~A~% tss= ~A~% tol= ~A~% w= ~A~% n= ~A~% p= ~A~%"
250 ;; (send self :beta-coefficents (lm x y)) ;; FIXME!
251 (send self
:xtxinv
(xtxinv x
))
253 (setf (slot-value 'total-sum-of-squares
) tss
)
254 (setf (slot-value 'residual-sum-of-squares
)
255 (m* (ones 1 n
) (v* res res
)))))
257 (defmeth regression-model-proto
:needs-computing
(&optional set
)
258 "Message args: ( &optional set )
260 If value given, sets the flag for whether (re)computation is needed to
261 update the model fits."
263 (if set
(setf (slot-value 'beta-hat
) nil
))
264 (null (slot-value 'beta-hat
)))
266 (defmeth regression-model-proto
:display
()
269 Prints the least squares regression summary. Variables not used in the fit
270 are marked as aliased."
271 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
272 (se-s (send self
:coef-standard-errors
))
274 (p-names (send self
:predictor-names
)))
275 (if (send self
:weights
)
276 (format t
"~%Weighted Least Squares Estimates:~2%")
277 (format t
"~%Least Squares Estimates:~2%"))
278 (when (send self
:intercept
)
279 (format t
"Constant ~10f ~A~%"
280 (car coefs
) (list (car se-s
)))
281 (setf coefs
(cdr coefs
))
282 (setf se-s
(cdr se-s
)))
283 (dotimes (i (array-dimension x
1))
285 ((member i
(send self
:basis
))
286 (format t
"~22a ~10f ~A~%"
287 (select p-names i
) (car coefs
) (list (car se-s
)))
288 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
289 (t (format t
"~22a aliased~%" (select p-names i
)))))
291 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
292 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
293 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
294 (if (/= (send self
:num-cases
) (send self
:num-included
))
295 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
296 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
299 ;;; Slot accessors and mutators
301 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
302 "Message args: (&optional new-doc)
304 Returns the DOC-STRING as supplied to m.
305 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
306 NEW-DOC. In this setting, when APPEND is T, don't replace and just
307 append NEW-DOC to DOC."
309 (when (and new-doc
(stringp new-doc
))
310 (setf (slot-value 'doc
)
319 (defmeth regression-model-proto
:x
(&optional new-x
)
320 "Message args: (&optional new-x)
322 With no argument returns the x matrix-like as supplied to m. With an
323 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
325 (when (and new-x
(typep new-x
'matrix-like
))
326 (setf (slot-value 'x
) new-x
)
327 (send self
:needs-computing t
))
330 (defmeth regression-model-proto
:y
(&optional new-y
)
331 "Message args: (&optional new-y)
333 With no argument returns the y vector-like as supplied to m. With an
334 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
337 (typep new-y
'vector-like
))
338 (setf (slot-value 'y
) new-y
) ;; fixme -- pls set slot value to a vector-like!
339 (send self
:needs-computing t
))
342 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
343 "Message args: (&optional new-intercept)
345 With no argument returns T if the model includes an intercept term,
346 nil if not. With an argument NEW-INTERCEPT the model is changed to
347 include or exclude an intercept, according to the value of
350 (setf (slot-value 'intercept
) val
)
351 (send self
:needs-computing t
))
352 (slot-value 'intercept
))
354 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
355 "Message args: (&optional new-w)
357 With no argument returns the weight vector-like as supplied to m; NIL
358 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
359 and recomputes the estimates."
361 #|
;; probably need to use "check-type" or similar?
364 (typep new-w
'vector-like
)))
366 (setf (slot-value 'weights
) new-w
)
367 (send self
:needs-computing t
))
368 (slot-value 'weights
))
370 (defmeth regression-model-proto
:total-sum-of-squares
()
373 Returns the total sum of squares around the mean.
374 This is recomputed if an update is needed."
375 (if (send self
:needs-computing
)
376 (send self
:compute
))
377 (slot-value 'total-sum-of-squares
))
379 (defmeth regression-model-proto
:residual-sum-of-squares
()
382 Returns the residual sum of squares for the model.
383 This is recomputed if an update is needed."
384 (if (send self
:needs-computing
)
385 (send self
:compute
))
386 (slot-value 'residual-sum-of-squares
))
388 (defmeth regression-model-proto
:basis
()
391 Returns the indices of the variables used in fitting the model, in a
393 This is recomputed if an update is needed."
394 (if (send self
:needs-computing
)
395 (send self
:compute
))
398 (defmeth regression-model-proto
:included
(&optional new-included
)
399 "Message args: (&optional new-included)
401 With no argument, NIL means a case is not used in calculating
402 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
403 of length of y of nil and t to select cases. Estimates are
408 (= (length new-included
) (send self
:num-cases
)))
410 (setf (slot-value 'included
) (copy-seq new-included
))
411 (send self
:needs-computing t
))
412 (if (slot-value 'included
)
413 (slot-value 'included
)
414 (repeat t
(send self
:num-cases
))))
416 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
417 "Message args: (&optional (names nil set))
419 With no argument returns the predictor names. NAMES sets the names."
420 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
421 (let ((p (matrix-dimension (send self
:x
) 1))
422 (p-names (slot-value 'predictor-names
)))
423 (if (not (and p-names
(= (length p-names
) p
)))
424 (setf (slot-value 'predictor-names
)
425 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
427 (slot-value 'predictor-names
))
429 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
430 "Message args: (&optional name)
432 With no argument returns the response name. NAME sets the name."
434 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
435 (slot-value 'response-name
))
437 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
438 "Message args: (&optional labels)
439 With no argument returns the case-labels. LABELS sets the labels."
440 (if set
(setf (slot-value 'case-labels
)
442 (mapcar #'string labels
)
443 (mapcar #'(lambda (x) (format nil
"~d" x
))
444 (iseq 0 (- (send self
:num-cases
) 1))))))
445 (slot-value 'case-labels
))
449 ;;; None of these methods access any slots directly.
452 (defmeth regression-model-proto
:num-cases
()
454 Returns the number of cases in the model."
455 (nelts (send self
:y
))) ; # cases in data, must accomodate weights or masking!
457 (defmeth regression-model-proto
:num-included
()
459 Returns the number of cases used in the computations."
460 (sum (if-else (send self
:included
) 1 0)))
462 (defmeth regression-model-proto
:num-coefs
()
464 Returns the number of coefficients in the fit model (including the
465 intercept if the model includes one)."
466 (if (send self
:intercept
)
467 (+ 1 (nelts (send self
:basis
)))
468 (nelts (send self
:basis
))))
470 (defmeth regression-model-proto
:df
()
472 Returns the number of degrees of freedom in the model."
473 (- (send self
:num-included
) (send self
:num-coefs
)))
475 (defmeth regression-model-proto
:x-matrix
()
477 Returns the X matrix for the model, including a column of 1's, if
478 appropriate. Columns of X matrix correspond to entries in basis."
479 (let ((m (select (send self
:x
)
480 (iseq 0 (- (send self
:num-cases
) 1))
481 (send self
:basis
))))
482 (if (send self
:intercept
)
483 (bind2 (repeat 1 (send self
:num-cases
)) m
)
486 (defmeth regression-model-proto
:leverages
()
488 Returns the diagonal elements of the hat matrix."
489 (let* ((weights (send self
:weights
))
490 (x (send self
:x-matrix
))
492 (m* (* (m* x
(send self
:xtxinv
)) x
)
493 (repeat 1 (send self
:num-coefs
)))))
494 (if weights
(* weights raw-levs
) raw-levs
)))
496 (defmeth regression-model-proto
:fit-values
()
498 Returns the fitted values for the model."
499 (m* (send self
:x-matrix
) (send self
:coef-estimates
)))
501 (defmeth regression-model-proto
:raw-residuals
()
503 Returns the raw residuals for a model."
504 (- (send self
:y
) (send self
:fit-values
)))
506 (defmeth regression-model-proto
:residuals
()
508 Returns the raw residuals for a model without weights. If the model
509 includes weights the raw residuals times the square roots of the weights
511 (let ((raw-residuals (send self
:raw-residuals
))
512 (weights (send self
:weights
)))
513 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
515 (defmeth regression-model-proto
:sum-of-squares
()
517 Returns the error sum of squares for the model."
518 (send self
:residual-sum-of-squares
))
520 (defmeth regression-model-proto
:sigma-hat
()
522 Returns the estimated standard deviation of the deviations about the
524 (let ((ss (send self
:sum-of-squares
))
525 (df (send self
:df
)))
526 (if (/= df
0) (sqrt (/ ss df
)))))
528 ;; for models without an intercept the 'usual' formula for R^2 can give
529 ;; negative results; hence the max.
530 (defmeth regression-model-proto
:r-squared
()
532 Returns the sample squared multiple correlation coefficient, R squared, for
534 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
537 (defmeth regression-model-proto
:coef-estimates
()
540 Returns the OLS (ordinary least squares) estimates of the regression
541 coefficients. Entries beyond the intercept correspond to entries in
543 (let ((n (matrix-dimension (send self
:x
) 1))
544 (indices (flatten-list
545 (if (send self
:intercept
)
546 (cons 0 (+ 1 (send self
:basis
)))
547 (list (+ 1 (send self
:basis
))))))
549 (format t
"~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
550 x n indices
(send self
:basis
))
551 (coerce (compound-data-seq (select m
(1+ n
) indices
)) 'list
))) ;; ERROR
553 (defmeth regression-model-proto
:xtxinv
()
555 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
556 (xtxinv (send self x
)))
558 (defmeth regression-model-proto
:coef-standard-errors
()
560 Returns estimated standard errors of coefficients. Entries beyond the
561 intercept correspond to entries in basis."
562 (let ((s (send self
:sigma-hat
)))
563 (if s
(* (send self
:sigma-hat
) (sqrt (diagonalf (send self
:xtxinv
)))))))
565 (defmeth regression-model-proto
:studentized-residuals
()
567 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
568 (let ((res (send self
:residuals
))
569 (lev (send self
:leverages
))
570 (sig (send self
:sigma-hat
))
571 (inc (send self
:included
)))
573 (/ res
(* sig
(sqrt (max .00001 (- 1 lev
))))) ; vectorize max
574 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
576 (defmeth regression-model-proto
:externally-studentized-residuals
()
578 Computes the externally studentized residuals."
579 (let* ((res (send self
:studentized-residuals
))
580 (df (send self
:df
)))
581 (if-else (send self
:included
)
582 (* res
(sqrt (/ (- df
1) (- df
(v* res res
)))))
585 (defmeth regression-model-proto
:cooks-distances
()
587 Computes Cook's distances."
588 (let ((lev (send self
:leverages
))
589 (res (/ (v* (send self
:studentized-residuals
)
590 (send self
:studentized-residuals
))
591 (send self
:num-coefs
))))
592 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
595 (defun plot-points (x y
&rest args
)
597 (error "Graphics not implemented yet."))
602 ;; Can not plot points yet!!
603 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
604 "Message args: (&optional x-values)
605 Opens a window with a plot of the residuals. If X-VALUES are not supplied
606 the fitted values are used. The plot can be linked to other plots with the
607 link-views function. Returns a plot object."
608 (plot-points (if x-values x-values
(send self
:fit-values
))
609 (send self
:residuals
)
610 :title
"Residual Plot"
611 :point-labels
(send self
:case-labels
)))
615 (defmeth regression-model-proto
:plot-bayes-residuals
617 "Message args: (&optional x-values)
619 Opens a window with a plot of the standardized residuals and two
620 standard error bars for the posterior distribution of the actual
621 deviations from the line. See Chaloner and Brant. If X-VALUES are not
622 supplied the fitted values are used. The plot can be linked to other
623 plots with the link-views function. Returns a plot object."
625 (let* ((r (/ (send self
:residuals
)
626 (send self
:sigma-hat
)))
627 (d (* 2 (sqrt (send self
:leverages
))))
630 (x-values (if x-values x-values
(send self
:fit-values
)))
631 (p (plot-points x-values r
632 :title
"Bayes Residual Plot"
633 :point-labels
(send self
:case-labels
))))
634 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
635 x-values low x-values high
)
636 (send p
:adjust-to-data
)
643 (defun print-lm (lm-obj)
647 ;; EVIL LOGIC! Just to store for now.
649 (n (length (residuals lm-obj
)))
650 (w (if (weights lm-obj
)
653 (r (if (weights lm-obj
)
655 (v.
* (residuals lm-obj
)
656 (mapcar #'sqrt
(weights lm-obj
)))))
657 (rss (sum (v.
* r r
)))
658 (resvar (/ rss
(- n p
)))
659 ;; then answer, to be encapsulated in a struct/class
661 (aliased (is.na
(coef lm-obj
)))
663 (df (list 0 n
(length aliased
)))
664 (coefficients (list 'NA
0d0
4d0
))o
665 (sigma (sqrt resvar
))
667 (adj.r.squared
0d0
)))
671 (let ((n (nrows (qr lm-obj
)))
676 (lm (transpose *xv
*) *y2
*)
678 (princ "Linear Models Code setup")