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 (make-vector (nrows x
) :type
:column
:initial-element
0d0
)) ; (compute-residuals y yhat)
243 ;; (* 0.001 (reduce #'* (mapcar #'standard-deviation (list-of-columns x))))
246 "~%REMVME: regr-mdl-prto :compute~%x= ~A~%y= ~A~% tss= ~A~% tol= ~A~% w= ~A~% n= ~A~% res= ~A~%"
247 x y tss tol w n p res
)
249 ;; (send self :beta-coefficents (lm x y)) ;; FIXME!
250 ;; (send self :xtxinv (xtxinv x)) ;; not settable?
252 (setf (proto-slot-value 'total-sum-of-squares
) tss
)
253 (setf (proto-slot-value 'residual-sum-of-squares
)
255 ;; (m* (ones 1 n) (v* res res))
258 (defmeth regression-model-proto
:needs-computing
(&optional set
)
259 "Message args: ( &optional set )
261 If value given, sets the flag for whether (re)computation is needed to
262 update the model fits."
264 (if set
(setf (proto-slot-value 'betahat
) nil
))
265 (null (proto-slot-value 'betahat
)))
267 (defmeth regression-model-proto
:display
()
270 Prints the least squares regression summary. Variables not used in the fit
271 are marked as aliased."
272 (let ((coefs (vector-like->list
(send self
:coef-estimates
)))
273 (se-s (send self
:coef-standard-errors
))
275 (p-names (send self
:predictor-names
)))
276 (if (send self
:weights
)
277 (format t
"~%Weighted Least Squares Estimates:~2%")
278 (format t
"~%Least Squares Estimates:~2%"))
279 (when (send self
:intercept
)
280 (format t
"Constant ~10f ~A~%"
281 (car coefs
) (list (car se-s
)))
282 (setf coefs
(cdr coefs
))
283 (setf se-s
(cdr se-s
)))
284 (dotimes (i (array-dimension x
1))
286 ((member i
(send self
:basis
))
287 (format t
"~22a ~10f ~A~%"
288 (select p-names i
) (car coefs
) (list (car se-s
)))
289 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
290 (t (format t
"~22a aliased~%" (select p-names i
)))))
292 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
293 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
294 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
295 (if (/= (send self
:num-cases
) (send self
:num-included
))
296 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
297 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
300 ;;; Slot accessors and mutators
302 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
303 "Message args: (&optional new-doc)
305 Returns the DOC-STRING as supplied to m.
306 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
307 NEW-DOC. In this setting, when APPEND is T, don't replace and just
308 append NEW-DOC to DOC."
310 (when (and new-doc
(stringp new-doc
))
311 (setf (proto-slot-value 'doc
)
314 (proto-slot-value 'doc
)
317 (proto-slot-value 'doc
))
320 (defmeth regression-model-proto
:x
(&optional new-x
)
321 "Message args: (&optional new-x)
323 With no argument returns the x matrix-like as supplied to m. With an
324 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
326 (when (and new-x
(typep new-x
'matrix-like
))
327 (setf (proto-slot-value 'x
) new-x
)
328 (send self
:needs-computing t
))
329 (proto-slot-value 'x
))
331 (defmeth regression-model-proto
:y
(&optional new-y
)
332 "Message args: (&optional new-y)
334 With no argument returns the y vector-like as supplied to m. With an
335 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
338 (typep new-y
'vector-like
))
339 (setf (proto-slot-value 'y
) new-y
) ;; fixme -- pls set slot value to a vector-like!
340 (send self
:needs-computing t
))
341 (proto-slot-value 'y
))
343 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
344 "Message args: (&optional new-intercept)
346 With no argument returns T if the model includes an intercept term,
347 nil if not. With an argument NEW-INTERCEPT the model is changed to
348 include or exclude an intercept, according to the value of
351 (setf (proto-slot-value 'intercept
) val
)
352 (send self
:needs-computing t
))
353 (proto-slot-value 'intercept
))
355 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
356 "Message args: (&optional new-w)
358 With no argument returns the weight vector-like as supplied to m; NIL
359 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
360 and recomputes the estimates."
362 #|
;; probably need to use "check-type" or similar?
365 (typep new-w
'vector-like
)))
367 (setf (proto-slot-value 'weights
) new-w
)
368 (send self
:needs-computing t
))
369 (proto-slot-value 'weights
))
371 (defmeth regression-model-proto
:total-sum-of-squares
()
374 Returns the total sum of squares around the mean.
375 This is recomputed if an update is needed."
376 (if (send self
:needs-computing
)
377 (send self
:compute
))
378 (proto-slot-value 'total-sum-of-squares
))
380 (defmeth regression-model-proto
:residual-sum-of-squares
()
383 Returns the residual sum of squares for the model.
384 This is recomputed if an update is needed."
385 (if (send self
:needs-computing
)
386 (send self
:compute
))
387 (proto-slot-value 'residual-sum-of-squares
))
389 (defmeth regression-model-proto
:basis
()
392 Returns the indices of the variables used in fitting the model, in a
394 This is recomputed if an update is needed."
395 (if (send self
:needs-computing
)
396 (send self
:compute
))
397 (proto-slot-value 'basis
))
399 (defmeth regression-model-proto
:included
(&optional new-included
)
400 "Message args: (&optional new-included)
402 With no argument, NIL means a case is not used in calculating
403 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
404 of length of y of nil and t to select cases. Estimates are
409 (= (length new-included
) (send self
:num-cases
)))
411 (setf (proto-slot-value 'included
) (copy-seq new-included
))
412 (send self
:needs-computing t
))
413 (if (proto-slot-value 'included
)
414 (proto-slot-value 'included
)
415 (repeat t
(send self
:num-cases
))))
417 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
418 "Message args: (&optional (names nil set))
420 With no argument returns the predictor names. NAMES sets the names."
421 (if set
(setf (proto-slot-value 'predictor-names
) (mapcar #'string names
)))
422 (let ((p (matrix-dimension (send self
:x
) 1))
423 (p-names (proto-slot-value 'predictor-names
)))
424 (if (not (and p-names
(= (length p-names
) p
)))
425 (setf (proto-slot-value 'predictor-names
)
426 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
428 (proto-slot-value 'predictor-names
))
430 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
431 "Message args: (&optional name)
433 With no argument returns the response name. NAME sets the name."
435 (if set
(setf (proto-slot-value 'response-name
) (if name
(string name
) "Y")))
436 (proto-slot-value 'response-name
))
438 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
439 "Message args: (&optional labels)
440 With no argument returns the case-labels. LABELS sets the labels."
441 (if set
(setf (proto-slot-value 'case-labels
)
443 (mapcar #'string labels
)
444 (mapcar #'(lambda (x) (format nil
"~d" x
))
445 (iseq 0 (- (send self
:num-cases
) 1))))))
446 (proto-slot-value 'case-labels
))
450 ;;; None of these methods access any slots directly.
453 (defmeth regression-model-proto
:num-cases
()
455 Returns the number of cases in the model."
456 (nelts (send self
:y
))) ; # cases in data, must accomodate weights or masking!
458 (defmeth regression-model-proto
:num-included
()
460 Returns the number of cases used in the computations."
461 (sum (if-else (send self
:included
) 1 0)))
463 (defmeth regression-model-proto
:num-coefs
()
465 Returns the number of coefficients in the fit model (including the
466 intercept if the model includes one)."
467 (if (send self
:intercept
)
468 (+ 1 (ncols (send self
:x
)))
469 (ncols (send self
:x
))))
471 (defmeth regression-model-proto
:df
()
473 Returns the number of degrees of freedom in the model."
474 (- (send self
:num-included
) (send self
:num-coefs
)))
476 (defmeth regression-model-proto
:x-matrix
()
478 Returns the X matrix for the model, including a column of 1's, if
479 appropriate. Columns of X matrix correspond to entries in basis."
480 (let ((m (select (send self
:x
)
481 (iseq 0 (- (send self
:num-cases
) 1))
482 (send self
:basis
))))
483 (if (send self
:intercept
)
484 (bind2 (repeat 1 (send self
:num-cases
)) m
)
487 (defmeth regression-model-proto
:leverages
()
489 Returns the diagonal elements of the hat matrix."
490 (let* ((x (send self
:x-matrix
))
495 (repeat 1 (send self
:num-coefs
)))))
496 (if (send self
:weights
)
497 (m* (send self
:weights
) raw-levs
)
500 (defmeth regression-model-proto
:fit-values
()
502 Returns the fitted values for the model."
503 (m* (send self
:x-matrix
)
504 (send self
:coef-estimates
)))
506 (defmeth regression-model-proto
:raw-residuals
()
508 Returns the raw residuals for a model."
509 (v- (send self
:y
) (send self
:fit-values
)))
511 (defmeth regression-model-proto
:residuals
()
513 Returns the raw residuals for a model without weights. If the model
514 includes weights the raw residuals times the square roots of the weights
516 (let ((raw-residuals (send self
:raw-residuals
))
517 (weights (send self
:weights
)))
518 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
520 (defmeth regression-model-proto
:sum-of-squares
()
522 Returns the error sum of squares for the model."
523 (send self
:residual-sum-of-squares
))
525 (defmeth regression-model-proto
:sigma-hat
()
527 Returns the estimated standard deviation of the deviations about the
529 (let ((ss (send self
:sum-of-squares
))
530 (df (send self
:df
)))
531 (if (/= df
0) (sqrt (/ ss df
)))))
533 ;; for models without an intercept the 'usual' formula for R^2 can give
534 ;; negative results; hence the max.
535 (defmeth regression-model-proto
:r-squared
()
537 Returns the sample squared multiple correlation coefficient, R squared, for
539 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
542 (defmeth regression-model-proto
:coef-estimates
()
545 Returns the OLS (ordinary least squares) estimates of the regression
546 coefficients. Entries beyond the intercept correspond to entries in
548 (let ((x (send self
:x
)))
551 (let ((n (matrix-dimension (send self
:x
) 1))
552 (indices (flatten-list
553 (if (send self
:intercept
)
554 (cons 0 (+ 1 (send self
:basis
)))
555 (list (+ 1 (send self
:basis
))))))
557 (format t
"~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
558 x n indices
(send self
:basis
))
559 (coerce (compound-data-seq (select m
(1+ n
) indices
)) 'list
))) ;; ERROR
562 (defmeth regression-model-proto
:xtxinv
()
564 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
565 (xtxinv (send self x
)))
567 (defmeth regression-model-proto
:coef-standard-errors
()
569 Returns estimated standard errors of coefficients. Entries beyond the
570 intercept correspond to entries in basis."
571 (let ((s (send self
:sigma-hat
)))
572 (if s
(* (send self
:sigma-hat
) (sqrt (diagonalf (send self
:xtxinv
)))))))
574 (defmeth regression-model-proto
:studentized-residuals
()
576 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
577 (let ((res (send self
:residuals
))
578 (lev (send self
:leverages
))
579 (sig (send self
:sigma-hat
))
580 (inc (send self
:included
)))
582 (/ res
(* sig
(sqrt (max .00001 (- 1 lev
))))) ; vectorize max
583 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
585 (defmeth regression-model-proto
:externally-studentized-residuals
()
587 Computes the externally studentized residuals."
588 (let* ((res (send self
:studentized-residuals
))
589 (df (send self
:df
)))
590 (if-else (send self
:included
)
591 (* res
(sqrt (/ (- df
1) (- df
(v* res res
)))))
594 (defmeth regression-model-proto
:cooks-distances
()
596 Computes Cook's distances."
597 (let ((lev (send self
:leverages
))
598 (res (/ (v* (send self
:studentized-residuals
)
599 (send self
:studentized-residuals
))
600 (send self
:num-coefs
))))
601 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
604 (defun plot-points (x y
&rest args
)
606 (error "Graphics not implemented yet."))
611 ;; Can not plot points yet!!
612 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
613 "Message args: (&optional x-values)
614 Opens a window with a plot of the residuals. If X-VALUES are not supplied
615 the fitted values are used. The plot can be linked to other plots with the
616 link-views function. Returns a plot object."
617 (plot-points (if x-values x-values
(send self
:fit-values
))
618 (send self
:residuals
)
619 :title
"Residual Plot"
620 :point-labels
(send self
:case-labels
)))
624 (defmeth regression-model-proto
:plot-bayes-residuals
626 "Message args: (&optional x-values)
628 Opens a window with a plot of the standardized residuals and two
629 standard error bars for the posterior distribution of the actual
630 deviations from the line. See Chaloner and Brant. If X-VALUES are not
631 supplied the fitted values are used. The plot can be linked to other
632 plots with the link-views function. Returns a plot object."
634 (let* ((r (/ (send self
:residuals
)
635 (send self
:sigma-hat
)))
636 (d (* 2 (sqrt (send self
:leverages
))))
639 (x-values (if x-values x-values
(send self
:fit-values
)))
640 (p (plot-points x-values r
641 :title
"Bayes Residual Plot"
642 :point-labels
(send self
:case-labels
))))
643 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
644 x-values low x-values high
)
645 (send p
:adjust-to-data
)
652 (defun print-lm (lm-obj)
656 ;; EVIL LOGIC! Just to store for now.
658 (n (length (residuals lm-obj
)))
659 (w (if (weights lm-obj
)
662 (r (if (weights lm-obj
)
664 (v.
* (residuals lm-obj
)
665 (mapcar #'sqrt
(weights lm-obj
)))))
666 (rss (sum (v.
* r r
)))
667 (resvar (/ rss
(- n p
)))
668 ;; then answer, to be encapsulated in a struct/class
670 (aliased (is.na
(coef lm-obj
)))
672 (df (list 0 n
(length aliased
)))
673 (coefficients (list 'NA
0d0
4d0
))o
674 (sigma (sqrt resvar
))
676 (adj.r.squared
0d0
)))
680 (let ((n (nrows (qr lm-obj
)))
685 (lm (transpose *xv
*) *y2
*)
687 (princ "Linear Models Code setup")