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 (m (make-sweep-matrix x y w
)) ;;; ERROR HERE of course!
236 (n (matrix-dimension x
1))
238 (1- (matrix-dimension m
0))
239 (matrix-dimension m
0))) ;; remove intercept from # params -- right?
240 (tss ) ; recompute, since we aren't sweeping...
242 (reduce #'* (mapcar #'standard-deviation
243 (list-of-columns x
))))))
245 "~%REMOVEME: regr-mdl-prto :compute~%Sweep= ~A~%x= ~A~%y= ~A~%m= ~A~%tss= ~A~%"
246 sweep-result x y m tss
)
248 (send self
:beta-coefficents
(lm x y
))
249 (send self
:xtxinv
(xtxinv x
)) ;; could extract from (lm ...)
251 (setf (slot-value 'sweep-matrix
) (first sweep-result
))
252 (setf (slot-value 'total-sum-of-squares
) tss
)
253 (setf (slot-value 'residual-sum-of-squares
)
254 (mref (first sweep-result
) p p
))
255 ;; SOMETHING WRONG HERE! FIX-ME
256 (setf (slot-value 'basis
)
257 (let ((b (remove 0 (second sweep-result
))))
258 (if b
(- (reduce #'-
(reverse b
)) 1)
259 (error "no columns could be swept"))))))
261 (defmeth regression-model-proto
:needs-computing
(&optional set
)
262 "Message args: ( &optional set )
264 If value given, sets the flag for whether (re)computation is needed to
265 update the model fits."
267 (if set
(setf (slot-value 'sweep-matrix
) nil
))
268 (null (slot-value 'sweep-matrix
)))
270 (defmeth regression-model-proto
:display
()
273 Prints the least squares regression summary. Variables not used in the fit
274 are marked as aliased."
275 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
276 (se-s (send self
:coef-standard-errors
))
278 (p-names (send self
:predictor-names
)))
279 (if (send self
:weights
)
280 (format t
"~%Weighted Least Squares Estimates:~2%")
281 (format t
"~%Least Squares Estimates:~2%"))
282 (when (send self
:intercept
)
283 (format t
"Constant ~10f ~A~%"
284 (car coefs
) (list (car se-s
)))
285 (setf coefs
(cdr coefs
))
286 (setf se-s
(cdr se-s
)))
287 (dotimes (i (array-dimension x
1))
289 ((member i
(send self
:basis
))
290 (format t
"~22a ~10f ~A~%"
291 (select p-names i
) (car coefs
) (list (car se-s
)))
292 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
293 (t (format t
"~22a aliased~%" (select p-names i
)))))
295 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
296 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
297 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
298 (if (/= (send self
:num-cases
) (send self
:num-included
))
299 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
300 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
303 ;;; Slot accessors and mutators
305 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
306 "Message args: (&optional new-doc)
308 Returns the DOC-STRING as supplied to m.
309 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
310 NEW-DOC. In this setting, when APPEND is T, don't replace and just
311 append NEW-DOC to DOC."
313 (when (and new-doc
(stringp new-doc
))
314 (setf (slot-value 'doc
)
323 (defmeth regression-model-proto
:x
(&optional new-x
)
324 "Message args: (&optional new-x)
326 With no argument returns the x matrix-like as supplied to m. With an
327 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
329 (when (and new-x
(typep new-x
'matrix-like
))
330 (setf (slot-value 'x
) new-x
)
331 (send self
:needs-computing t
))
334 (defmeth regression-model-proto
:y
(&optional new-y
)
335 "Message args: (&optional new-y)
337 With no argument returns the y vector-like as supplied to m. With an
338 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
341 (typep new-y
'vector-like
))
342 (setf (slot-value 'y
) new-y
) ;; fixme -- pls set slot value to a vector-like!
343 (send self
:needs-computing t
))
346 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
347 "Message args: (&optional new-intercept)
349 With no argument returns T if the model includes an intercept term,
350 nil if not. With an argument NEW-INTERCEPT the model is changed to
351 include or exclude an intercept, according to the value of
354 (setf (slot-value 'intercept
) val
)
355 (send self
:needs-computing t
))
356 (slot-value 'intercept
))
358 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
359 "Message args: (&optional new-w)
361 With no argument returns the weight vector-like as supplied to m; NIL
362 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
363 and recomputes the estimates."
365 #|
;; probably need to use "check-type" or similar?
368 (typep new-w
'vector-like
)))
370 (setf (slot-value 'weights
) new-w
)
371 (send self
:needs-computing t
))
372 (slot-value 'weights
))
374 (defmeth regression-model-proto
:total-sum-of-squares
()
377 Returns the total sum of squares around the mean.
378 This is recomputed if an update is needed."
379 (if (send self
:needs-computing
)
380 (send self
:compute
))
381 (slot-value 'total-sum-of-squares
))
383 (defmeth regression-model-proto
:residual-sum-of-squares
()
386 Returns the residual sum of squares for the model.
387 This is recomputed if an update is needed."
388 (if (send self
:needs-computing
)
389 (send self
:compute
))
390 (slot-value 'residual-sum-of-squares
))
392 (defmeth regression-model-proto
:basis
()
395 Returns the indices of the variables used in fitting the model, in a
397 This is recomputed if an update is needed."
398 (if (send self
:needs-computing
)
399 (send self
:compute
))
402 (defmeth regression-model-proto
:included
(&optional new-included
)
403 "Message args: (&optional new-included)
405 With no argument, NIL means a case is not used in calculating
406 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
407 of length of y of nil and t to select cases. Estimates are
412 (= (length new-included
) (send self
:num-cases
)))
414 (setf (slot-value 'included
) (copy-seq new-included
))
415 (send self
:needs-computing t
))
416 (if (slot-value 'included
)
417 (slot-value 'included
)
418 (repeat t
(send self
:num-cases
))))
420 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
421 "Message args: (&optional (names nil set))
423 With no argument returns the predictor names. NAMES sets the names."
424 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
425 (let ((p (matrix-dimension (send self
:x
) 1))
426 (p-names (slot-value 'predictor-names
)))
427 (if (not (and p-names
(= (length p-names
) p
)))
428 (setf (slot-value 'predictor-names
)
429 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
431 (slot-value 'predictor-names
))
433 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
434 "Message args: (&optional name)
436 With no argument returns the response name. NAME sets the name."
438 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
439 (slot-value 'response-name
))
441 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
442 "Message args: (&optional labels)
443 With no argument returns the case-labels. LABELS sets the labels."
444 (if set
(setf (slot-value 'case-labels
)
446 (mapcar #'string labels
)
447 (mapcar #'(lambda (x) (format nil
"~d" x
))
448 (iseq 0 (- (send self
:num-cases
) 1))))))
449 (slot-value 'case-labels
))
453 ;;; None of these methods access any slots directly.
456 (defmeth regression-model-proto
:num-cases
()
458 Returns the number of cases in the model."
459 (nelts (send self
:y
)))
461 (defmeth regression-model-proto
:num-included
()
463 Returns the number of cases used in the computations."
464 (sum (if-else (send self
:included
) 1 0)))
466 (defmeth regression-model-proto
:num-coefs
()
468 Returns the number of coefficients in the fit model (including the
469 intercept if the model includes one)."
470 (if (send self
:intercept
)
471 (+ 1 (nelts (send self
:basis
)))
472 (nelts (send self
:basis
))))
474 (defmeth regression-model-proto
:df
()
476 Returns the number of degrees of freedom in the model."
477 (- (send self
:num-included
) (send self
:num-coefs
)))
479 (defmeth regression-model-proto
:x-matrix
()
481 Returns the X matrix for the model, including a column of 1's, if
482 appropriate. Columns of X matrix correspond to entries in basis."
483 (let ((m (select (send self
:x
)
484 (iseq 0 (- (send self
:num-cases
) 1))
485 (send self
:basis
))))
486 (if (send self
:intercept
)
487 (bind2 (repeat 1 (send self
:num-cases
)) m
)
490 (defmeth regression-model-proto
:leverages
()
492 Returns the diagonal elements of the hat matrix."
493 (let* ((weights (send self
:weights
))
494 (x (send self
:x-matrix
))
496 (m* (* (m* x
(send self
:xtxinv
)) x
)
497 (repeat 1 (send self
:num-coefs
)))))
498 (if weights
(* weights raw-levs
) raw-levs
)))
500 (defmeth regression-model-proto
:fit-values
()
502 Returns the fitted values for the model."
503 (m* (send self
:x-matrix
) (send self
:coef-estimates
)))
505 (defmeth regression-model-proto
:raw-residuals
()
507 Returns the raw residuals for a model."
508 (- (send self
:y
) (send self
:fit-values
)))
510 (defmeth regression-model-proto
:residuals
()
512 Returns the raw residuals for a model without weights. If the model
513 includes weights the raw residuals times the square roots of the weights
515 (let ((raw-residuals (send self
:raw-residuals
))
516 (weights (send self
:weights
)))
517 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
519 (defmeth regression-model-proto
:sum-of-squares
()
521 Returns the error sum of squares for the model."
522 (send self
:residual-sum-of-squares
))
524 (defmeth regression-model-proto
:sigma-hat
()
526 Returns the estimated standard deviation of the deviations about the
528 (let ((ss (send self
:sum-of-squares
))
529 (df (send self
:df
)))
530 (if (/= df
0) (sqrt (/ ss df
)))))
532 ;; for models without an intercept the 'usual' formula for R^2 can give
533 ;; negative results; hence the max.
534 (defmeth regression-model-proto
:r-squared
()
536 Returns the sample squared multiple correlation coefficient, R squared, for
538 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
541 (defmeth regression-model-proto
:coef-estimates
()
544 Returns the OLS (ordinary least squares) estimates of the regression
545 coefficients. Entries beyond the intercept correspond to entries in
547 (let ((n (matrix-dimension (send self
:x
) 1))
548 (indices (flatten-list
549 (if (send self
:intercept
)
550 (cons 0 (+ 1 (send self
:basis
)))
551 (list (+ 1 (send self
:basis
))))))
552 (m (send self
:sweep-matrix
)))
553 (format t
"~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
554 m n indices
(send self
:basis
))
555 (coerce (compound-data-seq (select m
(1+ n
) indices
)) 'list
))) ;; ERROR
557 (defmeth regression-model-proto
:xtxinv
()
559 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
560 (xtxinv (send self x
)))
562 (defmeth regression-model-proto
:coef-standard-errors
()
564 Returns estimated standard errors of coefficients. Entries beyond the
565 intercept correspond to entries in basis."
566 (let ((s (send self
:sigma-hat
)))
567 (if s
(* (send self
:sigma-hat
) (sqrt (diagonalf (send self
:xtxinv
)))))))
569 (defmeth regression-model-proto
:studentized-residuals
()
571 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
572 (let ((res (send self
:residuals
))
573 (lev (send self
:leverages
))
574 (sig (send self
:sigma-hat
))
575 (inc (send self
:included
)))
577 (/ res
(* sig
(sqrt (max .00001 (- 1 lev
))))) ; vectorize max
578 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
580 (defmeth regression-model-proto
:externally-studentized-residuals
()
582 Computes the externally studentized residuals."
583 (let* ((res (send self
:studentized-residuals
))
584 (df (send self
:df
)))
585 (if-else (send self
:included
)
586 (* res
(sqrt (/ (- df
1) (- df
(^ res
2)))))
589 (defmeth regression-model-proto
:cooks-distances
()
591 Computes Cook's distances."
592 (let ((lev (send self
:leverages
))
593 (res (/ (^
(send self
:studentized-residuals
) 2)
594 (send self
:num-coefs
))))
595 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
598 (defun plot-points (x y
&rest args
)
600 (declare (ignore x y args
))
601 (error "Graphics not implemented yet."))
603 ;; Can not plot points yet!!
604 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
605 "Message args: (&optional x-values)
606 Opens a window with a plot of the residuals. If X-VALUES are not supplied
607 the fitted values are used. The plot can be linked to other plots with the
608 link-views function. Returns a plot object."
609 (plot-points (if x-values x-values
(send self
:fit-values
))
610 (send self
:residuals
)
611 :title
"Residual Plot"
612 :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")