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")
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
))))))
119 (defun regression-model
124 (included (repeat t
(vector-dimension y
)))
128 (doc "Undocumented Regression Model Instance")
130 "Args: (x y &key (intercept T) (print T) (weights nil)
131 included predictor-names response-name case-labels)
132 X - list of independent variables or X matrix
133 Y - dependent variable.
134 INTERCEPT - T to include (default), NIL for no intercept
135 PRINT - if not NIL print summary information
136 WEIGHTS - if supplied should be the same length as Y; error
138 assumed to be inversely proportional to WEIGHTS
139 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
140 - sequences of strings or symbols.
141 INCLUDED - if supplied should be the same length as Y, with
142 elements nil to skip a in computing estimates (but not
143 in residual analysis).
144 Returns a regression model object. To examine the model further assign the
145 result to a variable and send it messages.
146 Example (data are in file absorbtion.lsp in the sample data directory):
147 (def m (regression-model (list iron aluminum) absorbtion))
148 (send m :help) (send m :plot-residuals)"
150 ((typep x
'matrix-like
) x
)
151 #| assume only numerical vectors -- but we need to ensure coercion to float.
152 ((or (typep x
'sequence
)
155 (make-vector (length x
) :initial-contents x
)))
157 (t (error "not matrix-like.");x
158 ))) ;; actually, might should barf.
160 ((typep y
'vector-like
) y
)
163 (numberp (car x
))) (make-vector (length y
) :initial-contents y
))
165 (t (error "not vector-like."); y
166 ))) ;; actually, might should barf.
167 (m (send regression-model-proto
:new
)))
172 (send m
:intercept intercept
)
173 (send m
:weights weights
)
174 (send m
:included included
)
175 (send m
:predictor-names predictor-names
)
176 (send m
:response-name response-name
)
177 (send m
:case-labels case-labels
)
181 (format t
"~S~%" (send m
:doc
))
182 (format t
"X: ~S~%" (send m
:x
))
183 (format t
"Y: ~S~%" (send m
:y
))))
184 (if print
(send m
:display
))
190 (defmeth regression-model-proto
:isnew
()
191 (send self
:needs-computing t
))
193 (defmeth regression-model-proto
:save
()
195 Returns an expression that will reconstruct the regression model."
196 `(regression-model ',(send self
:x
)
198 :intercept
',(send self
:intercept
)
199 :weights
',(send self
:weights
)
200 :included
',(send self
:included
)
201 :predictor-names
',(send self
:predictor-names
)
202 :response-name
',(send self
:response-name
)
203 :case-labels
',(send self
:case-labels
)))
205 ;;; Computing and Display Methods
210 ;; so with (= (dim X) (list n p))
211 ;; we end up with p x p p x 1
214 ;; and this can be implemented by
216 (setf XY
(bind2 X Y
:by
:row
))
217 (setf XYtXY
(m* (transpose XY
) XY
))
219 ;; which is too procedural. Sigh, I meant
221 (setf XYtXY
(let ((XY (bind2 X Y
:by
:row
)))
222 (m* (transpose XY
) XY
)))
224 ;; which at least looks lispy.
226 (defmeth regression-model-proto
:compute
()
228 Recomputes the estimates. For internal use by other messages"
229 (let* ((included (if-else (send self
:included
) 1d0
0d0
))
232 (intercept (send self
:intercept
)) ;; T/nil
233 (weights (send self
:weights
)) ;; vector-like or nil
234 (w (if weights
(* included weights
) included
))
235 (n (matrix-dimension x
0))
237 (1- (matrix-dimension x
1))
238 (matrix-dimension x
1))) ;; remove intercept from # params -- right?
240 (res 0 ; (compute-residuals y yhat)
243 (reduce #'* (mapcar #'standard-deviation
244 (list-of-columns x
))))))
246 "~%REMOVEME: regr-mdl-prto :compute~%x= ~A~%y= ~A~% tss= ~A~% tol= ~A~% w= ~A~% n= ~A~% p= ~A~%"
249 (send self
:beta-coefficents
(lm x y
))
250 (send self
:xtxinv
(xtxinv x
))
252 (setf (slot-value 'total-sum-of-squares
) tss
)
253 (setf (slot-value 'residual-sum-of-squares
)
254 (m* (ones 1 n
) (v* res res
)))))
256 (defmeth regression-model-proto
:needs-computing
(&optional set
)
257 "Message args: ( &optional set )
259 If value given, sets the flag for whether (re)computation is needed to
260 update the model fits."
262 (if set
(setf (slot-value 'sweep-matrix
) nil
))
263 (null (slot-value 'sweep-matrix
)))
265 (defmeth regression-model-proto
:display
()
268 Prints the least squares regression summary. Variables not used in the fit
269 are marked as aliased."
270 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
271 (se-s (send self
:coef-standard-errors
))
273 (p-names (send self
:predictor-names
)))
274 (if (send self
:weights
)
275 (format t
"~%Weighted Least Squares Estimates:~2%")
276 (format t
"~%Least Squares Estimates:~2%"))
277 (when (send self
:intercept
)
278 (format t
"Constant ~10f ~A~%"
279 (car coefs
) (list (car se-s
)))
280 (setf coefs
(cdr coefs
))
281 (setf se-s
(cdr se-s
)))
282 (dotimes (i (array-dimension x
1))
284 ((member i
(send self
:basis
))
285 (format t
"~22a ~10f ~A~%"
286 (select p-names i
) (car coefs
) (list (car se-s
)))
287 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
288 (t (format t
"~22a aliased~%" (select p-names i
)))))
290 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
291 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
292 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
293 (if (/= (send self
:num-cases
) (send self
:num-included
))
294 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
295 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
298 ;;; Slot accessors and mutators
300 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
301 "Message args: (&optional new-doc)
303 Returns the DOC-STRING as supplied to m.
304 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
305 NEW-DOC. In this setting, when APPEND is T, don't replace and just
306 append NEW-DOC to DOC."
308 (when (and new-doc
(stringp new-doc
))
309 (setf (slot-value 'doc
)
318 (defmeth regression-model-proto
:x
(&optional new-x
)
319 "Message args: (&optional new-x)
321 With no argument returns the x matrix-like as supplied to m. With an
322 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
324 (when (and new-x
(typep new-x
'matrix-like
))
325 (setf (slot-value 'x
) new-x
)
326 (send self
:needs-computing t
))
329 (defmeth regression-model-proto
:y
(&optional new-y
)
330 "Message args: (&optional new-y)
332 With no argument returns the y vector-like as supplied to m. With an
333 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
336 (typep new-y
'vector-like
))
337 (setf (slot-value 'y
) new-y
) ;; fixme -- pls set slot value to a vector-like!
338 (send self
:needs-computing t
))
341 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
342 "Message args: (&optional new-intercept)
344 With no argument returns T if the model includes an intercept term,
345 nil if not. With an argument NEW-INTERCEPT the model is changed to
346 include or exclude an intercept, according to the value of
349 (setf (slot-value 'intercept
) val
)
350 (send self
:needs-computing t
))
351 (slot-value 'intercept
))
353 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
354 "Message args: (&optional new-w)
356 With no argument returns the weight vector-like as supplied to m; NIL
357 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
358 and recomputes the estimates."
360 #|
;; probably need to use "check-type" or similar?
363 (typep new-w
'vector-like
)))
365 (setf (slot-value 'weights
) new-w
)
366 (send self
:needs-computing t
))
367 (slot-value 'weights
))
369 (defmeth regression-model-proto
:total-sum-of-squares
()
372 Returns the total sum of squares around the mean.
373 This is recomputed if an update is needed."
374 (if (send self
:needs-computing
)
375 (send self
:compute
))
376 (slot-value 'total-sum-of-squares
))
378 (defmeth regression-model-proto
:residual-sum-of-squares
()
381 Returns the residual sum of squares for the model.
382 This is recomputed if an update is needed."
383 (if (send self
:needs-computing
)
384 (send self
:compute
))
385 (slot-value 'residual-sum-of-squares
))
387 (defmeth regression-model-proto
:basis
()
390 Returns the indices of the variables used in fitting the model, in a
392 This is recomputed if an update is needed."
393 (if (send self
:needs-computing
)
394 (send self
:compute
))
397 (defmeth regression-model-proto
:included
(&optional new-included
)
398 "Message args: (&optional new-included)
400 With no argument, NIL means a case is not used in calculating
401 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
402 of length of y of nil and t to select cases. Estimates are
407 (= (length new-included
) (send self
:num-cases
)))
409 (setf (slot-value 'included
) (copy-seq new-included
))
410 (send self
:needs-computing t
))
411 (if (slot-value 'included
)
412 (slot-value 'included
)
413 (repeat t
(send self
:num-cases
))))
415 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
416 "Message args: (&optional (names nil set))
418 With no argument returns the predictor names. NAMES sets the names."
419 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
420 (let ((p (matrix-dimension (send self
:x
) 1))
421 (p-names (slot-value 'predictor-names
)))
422 (if (not (and p-names
(= (length p-names
) p
)))
423 (setf (slot-value 'predictor-names
)
424 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
426 (slot-value 'predictor-names
))
428 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
429 "Message args: (&optional name)
431 With no argument returns the response name. NAME sets the name."
433 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
434 (slot-value 'response-name
))
436 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
437 "Message args: (&optional labels)
438 With no argument returns the case-labels. LABELS sets the labels."
439 (if set
(setf (slot-value 'case-labels
)
441 (mapcar #'string labels
)
442 (mapcar #'(lambda (x) (format nil
"~d" x
))
443 (iseq 0 (- (send self
:num-cases
) 1))))))
444 (slot-value 'case-labels
))
448 ;;; None of these methods access any slots directly.
451 (defmeth regression-model-proto
:num-cases
()
453 Returns the number of cases in the model."
454 (nelts (send self
:y
)))
456 (defmeth regression-model-proto
:num-included
()
458 Returns the number of cases used in the computations."
459 (sum (if-else (send self
:included
) 1 0)))
461 (defmeth regression-model-proto
:num-coefs
()
463 Returns the number of coefficients in the fit model (including the
464 intercept if the model includes one)."
465 (if (send self
:intercept
)
466 (+ 1 (nelts (send self
:basis
)))
467 (nelts (send self
:basis
))))
469 (defmeth regression-model-proto
:df
()
471 Returns the number of degrees of freedom in the model."
472 (- (send self
:num-included
) (send self
:num-coefs
)))
474 (defmeth regression-model-proto
:x-matrix
()
476 Returns the X matrix for the model, including a column of 1's, if
477 appropriate. Columns of X matrix correspond to entries in basis."
478 (let ((m (select (send self
:x
)
479 (iseq 0 (- (send self
:num-cases
) 1))
480 (send self
:basis
))))
481 (if (send self
:intercept
)
482 (bind2 (repeat 1 (send self
:num-cases
)) m
)
485 (defmeth regression-model-proto
:leverages
()
487 Returns the diagonal elements of the hat matrix."
488 (let* ((weights (send self
:weights
))
489 (x (send self
:x-matrix
))
491 (m* (* (m* x
(send self
:xtxinv
)) x
)
492 (repeat 1 (send self
:num-coefs
)))))
493 (if weights
(* weights raw-levs
) raw-levs
)))
495 (defmeth regression-model-proto
:fit-values
()
497 Returns the fitted values for the model."
498 (m* (send self
:x-matrix
) (send self
:coef-estimates
)))
500 (defmeth regression-model-proto
:raw-residuals
()
502 Returns the raw residuals for a model."
503 (- (send self
:y
) (send self
:fit-values
)))
505 (defmeth regression-model-proto
:residuals
()
507 Returns the raw residuals for a model without weights. If the model
508 includes weights the raw residuals times the square roots of the weights
510 (let ((raw-residuals (send self
:raw-residuals
))
511 (weights (send self
:weights
)))
512 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
514 (defmeth regression-model-proto
:sum-of-squares
()
516 Returns the error sum of squares for the model."
517 (send self
:residual-sum-of-squares
))
519 (defmeth regression-model-proto
:sigma-hat
()
521 Returns the estimated standard deviation of the deviations about the
523 (let ((ss (send self
:sum-of-squares
))
524 (df (send self
:df
)))
525 (if (/= df
0) (sqrt (/ ss df
)))))
527 ;; for models without an intercept the 'usual' formula for R^2 can give
528 ;; negative results; hence the max.
529 (defmeth regression-model-proto
:r-squared
()
531 Returns the sample squared multiple correlation coefficient, R squared, for
533 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
536 (defmeth regression-model-proto
:coef-estimates
()
539 Returns the OLS (ordinary least squares) estimates of the regression
540 coefficients. Entries beyond the intercept correspond to entries in
542 (let ((n (matrix-dimension (send self
:x
) 1))
543 (indices (flatten-list
544 (if (send self
:intercept
)
545 (cons 0 (+ 1 (send self
:basis
)))
546 (list (+ 1 (send self
:basis
))))))
547 (m (send self
:sweep-matrix
)))
548 (format t
"~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
549 m n indices
(send self
:basis
))
550 (coerce (compound-data-seq (select m
(1+ n
) indices
)) 'list
))) ;; ERROR
552 (defmeth regression-model-proto
:xtxinv
()
554 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
555 (xtxinv (send self x
)))
557 (defmeth regression-model-proto
:coef-standard-errors
()
559 Returns estimated standard errors of coefficients. Entries beyond the
560 intercept correspond to entries in basis."
561 (let ((s (send self
:sigma-hat
)))
562 (if s
(* (send self
:sigma-hat
) (sqrt (diagonalf (send self
:xtxinv
)))))))
564 (defmeth regression-model-proto
:studentized-residuals
()
566 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
567 (let ((res (send self
:residuals
))
568 (lev (send self
:leverages
))
569 (sig (send self
:sigma-hat
))
570 (inc (send self
:included
)))
572 (/ res
(* sig
(sqrt (max .00001 (- 1 lev
))))) ; vectorize max
573 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
575 (defmeth regression-model-proto
:externally-studentized-residuals
()
577 Computes the externally studentized residuals."
578 (let* ((res (send self
:studentized-residuals
))
579 (df (send self
:df
)))
580 (if-else (send self
:included
)
581 (* res
(sqrt (/ (- df
1) (- df
(v* res res
)))))
584 (defmeth regression-model-proto
:cooks-distances
()
586 Computes Cook's distances."
587 (let ((lev (send self
:leverages
))
588 (res (/ (v* (send self
:studentized-residuals
)
589 (send self
:studentized-residuals
))
590 (send self
:num-coefs
))))
591 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
594 (defun plot-points (x y
&rest args
)
596 (error "Graphics not implemented yet."))
601 ;; Can not plot points yet!!
602 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
603 "Message args: (&optional x-values)
604 Opens a window with a plot of the residuals. If X-VALUES are not supplied
605 the fitted values are used. The plot can be linked to other plots with the
606 link-views function. Returns a plot object."
607 (plot-points (if x-values x-values
(send self
:fit-values
))
608 (send self
:residuals
)
609 :title
"Residual Plot"
610 :point-labels
(send self
:case-labels
)))
614 (defmeth regression-model-proto
:plot-bayes-residuals
616 "Message args: (&optional x-values)
618 Opens a window with a plot of the standardized residuals and two
619 standard error bars for the posterior distribution of the actual
620 deviations from the line. See Chaloner and Brant. If X-VALUES are not
621 supplied the fitted values are used. The plot can be linked to other
622 plots with the link-views function. Returns a plot object."
624 (let* ((r (/ (send self
:residuals
)
625 (send self
:sigma-hat
)))
626 (d (* 2 (sqrt (send self
:leverages
))))
629 (x-values (if x-values x-values
(send self
:fit-values
)))
630 (p (plot-points x-values r
631 :title
"Bayes Residual Plot"
632 :point-labels
(send self
:case-labels
))))
633 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
634 x-values low x-values high
)
635 (send p
:adjust-to-data
)
642 (defun print-lm (lm-obj)
646 ;; EVIL LOGIC! Just to store for now.
648 (n (length (residuals lm-obj
)))
649 (w (if (weights lm-obj
)
652 (r (if (weights lm-obj
)
654 (v.
* (residuals lm-obj
)
655 (mapcar #'sqrt
(weights lm-obj
)))))
656 (rss (sum (v.
* r r
)))
657 (resvar (/ rss
(- n p
)))
658 ;; then answer, to be encapsulated in a struct/class
660 (aliased (is.na
(coef lm-obj
)))
662 (df (list 0 n
(length aliased
)))
663 (coefficients (list 'NA
0d0
4d0
))o
664 (sigma (sqrt resvar
))
666 (adj.r.squared
0d0
)))
670 (let ((n (nrows (qr lm-obj
)))
675 (lm (transpose *xv
*) *y2
*)
677 (princ "Linear Models Code setup")