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.")
39 (defproto regression-model-proto
40 '(x y intercept betahat
41 basis weights included
42 total-sum-of-squares residual-sum-of-squares
43 predictor-names response-name case-labels doc
)
44 () *object
* "Normal Linear Regression Model")
46 (defclass regression-model-class
() ; (statistical-model)
51 :accessor response-variable
56 :accessor design-matrix
67 :initarg
:covariate-names
68 :accessor covariate-names
72 :initarg
:response-name
73 :accessor response-name
85 (:documentation
"Normal Linear Regression Model with CLOS.
86 Historical design based on LispStat."))
89 (defclass regression-model-fit-class
()
95 :type regression-model-class
)
98 :initarg
:needs-computing
99 :accessor needs-computing
)
115 :initarg
:weight-types
116 :accessor weight-types
119 ;; computational artifacts
130 (estimates-covariance-matrix
132 :initarg
:estimates-covariance-matrix
133 :accessor covariation-matrix
135 (total-sum-of-squares
139 (residual-sum-of-squares
149 (:documentation
"Normal Linear Regression Model _FIT_ through CLOS."))
151 ;;;;;;;; Helper functions
156 X is NxP, resulting in PxP. Represents Var[\hat\beta], the varest for
157 \hat \beta from Y = X \beta + \eps. Done by Cholesky decomposition,
158 with LAPACK's dpotri routine, factorizing with dpotrf.
161 (let ((m1 (rand 7 5)))
164 (check-type x matrix-like
)
165 (minv-cholesky (m* (transpose x
) x
)))
168 ;; might add args: (method 'gelsy), or do we want to put a more
169 ;; general front end, linear-least-square, across the range of
171 (defun lm (x y
&key
(intercept T
) rcond
)
172 "fit the linear model:
175 and estimate \beta. X,Y should be in cases-by-vars form, i.e. X
176 should be n x p, Y should be n x 1. Returns estimates, n and p.
177 Probably should return a form providing the call, as well.
179 R's lm object returns: coefficients, residuals, effects, rank, fitted,
180 qr-results for numerical considerations, DF_resid. Need to
181 encapsulate into a class or struct."
182 (check-type x matrix-like
)
183 (check-type y vector-like
) ; vector-like might be too strict?
185 (= (nrows y
) (nrows x
)) ; same number of observations/cases
186 (x y
) "Can not multiply x:~S by y:~S" x y
)
187 (let ((x1 (if intercept
188 (bind2 (ones (matrix-dimension x
0) 1)
191 (let ((betahat (gelsy (m* (transpose x1
) x1
)
192 (m* (transpose x1
) y
)
194 (* (coerce (expt 2 -
52) 'double-float
)
200 (* (coerce (expt 2 -
52) 'double-float
)
203 ;; need computation for SEs,
205 (list betahat
; LA-SIMPLE-VECTOR-DOUBLE
206 betahat1
; LA-SLICE-VECVIEW-DOUBLE
207 (xtxinv x1
); (sebetahat betahat x y) ; TODO: write me!
208 (nrows x
) ; surrogate for n
209 (ncols x1
) ; surrogate for p
210 (v- (first betahat
) (first betahat1
)) ))))
213 (defun regression-model (x y
&key
(intercept T
)
214 (predictor-names nil
) (response-name nil
) (case-labels nil
)
215 (doc "Undocumented Regression Model Instance"))
216 "Args: (x y &key (intercept T) (print T) (weights nil)
217 included predictor-names response-name case-labels)
218 X - list of independent variables or X matrix
219 Y - dependent variable.
220 INTERCEPT - T to include (default), NIL for no intercept
221 PRINT - if not NIL print summary information
222 WEIGHTS - if supplied should be the same length as Y; error
224 assumed to be inversely proportional to WEIGHTS
225 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
226 - sequences of strings or symbols.
227 INCLUDED - if supplied, should be length Y or 1, with
228 elements nil to skip or T to include for computing estimates
229 (always included in residual analysis).
230 Returns a regression model object."
231 (check-type x matrix-like
)
232 (check-type y vector-like
)
233 (let ((newmodel (make-instance 'regression-model-class
236 :interceptp intercept
237 :case-labels case-labels
238 :covariate-names predictor-names
239 :response-name response-name
243 (defun fit-model (model &key
(included T
) (wgts nil
) (docs "No Docs"))
244 (let ((result (make-instance 'regression-model-fit-class
249 :estimates
(first (lm (design-matrix model
)
250 (response-variable model
)
251 :intercept
(interceptp model
)))
252 :estimates-covariance-matrix
(xtxinv (design-matrix model
))
256 ;(defmethod print-object (obj regression-model-class))
262 (defmeth regression-model-proto
:isnew
()
263 (send self
:needs-computing t
))
265 (defmeth regression-model-proto
:save
()
267 Returns an expression that will reconstruct the regression model."
268 `(regression-model ',(send self
:x
)
270 :intercept
',(send self
:intercept
)
271 :weights
',(send self
:weights
)
272 :included
',(send self
:included
)
273 :predictor-names
',(send self
:predictor-names
)
274 :response-name
',(send self
:response-name
)
275 :case-labels
',(send self
:case-labels
)))
277 ;;; Computing and Display Methods
282 ;; so with (= (dim X) (list n p))
283 ;; we end up with p x p p x 1
286 ;; and this can be implemented by
288 (setf XY
(bind2 X Y
:by
:row
))
289 (setf XYtXY
(m* (transpose XY
) XY
))
291 ;; which is too procedural. Sigh, I meant
293 (setf XYtXY
(let ((XY (bind2 X Y
:by
:row
)))
294 (m* (transpose XY
) XY
)))
296 ;; which at least looks lispy.
298 (defmeth regression-model-proto
:compute
()
300 Recomputes the estimates. For internal use by other messages"
301 (let* ((included (if-else (send self
:included
) 1d0
0d0
))
304 (intercept (send self
:intercept
)) ;; T/nil
305 (weights (send self
:weights
)) ;; vector-like or nil
306 (w (if weights
(* included weights
) included
))
307 (n (matrix-dimension x
0))
309 (1- (matrix-dimension x
1))
310 (matrix-dimension x
1))) ;; remove intercept from # params -- right?
312 (res (make-vector (nrows x
) :type
:column
:initial-element
0d0
)) ; (compute-residuals y yhat)
314 ;; (* 0.001 (reduce #'* (mapcar #'standard-deviation (list-of-columns x))))
317 "~%REMVME: regr-pr :compute~%x= ~A~%y= ~A~% tss= ~A~% tol= ~A~% w= ~A~% n= ~A~% res= ~A p=~A ~% "
318 x y tss tol w n res p
)
320 (setf (proto-slot-value 'betahat
)
321 (first (lm (send self
:x
)
322 (send self
:y
)))) ;; FIXME!
324 (setf (proto-slot-value 'total-sum-of-squares
) tss
)
325 (setf (proto-slot-value 'residual-sum-of-squares
)
327 ;; (m* (ones 1 n) (v* res res))
330 (defmeth regression-model-proto
:needs-computing
(&optional set
)
331 "Message args: ( &optional set )
333 If value given, sets the flag for whether (re)computation is needed to
334 update the model fits."
336 (if set
(setf (proto-slot-value 'betahat
) nil
))
337 (null (proto-slot-value 'betahat
)))
339 (defmeth regression-model-proto
:display
()
341 Prints the least squares regression summary. Variables not used in the fit
342 are marked as aliased."
344 (format nil
"Computing Regression Proto :display"))
347 (let ((coefs (vector-like->list
(send self
:coef-estimates
)))
348 (se-s (send self
:coef-standard-errors
))
350 (p-names (send self
:predictor-names
)))
351 (if (send self
:weights
)
352 (format t
"~%Weighted Least Squares Estimates:~2%")
353 (format t
"~%Least Squares Estimates:~2%"))
354 (when (send self
:intercept
)
355 (format t
"Constant ~10f ~A~%"
356 (car coefs
) (list (car se-s
)))
357 (setf coefs
(cdr coefs
))
358 (setf se-s
(cdr se-s
)))
359 (dotimes (i (array-dimension x
1))
361 ((member i
(send self
:basis
))
362 (format t
"~22a ~10f ~A~%"
363 (select p-names i
) (car coefs
) (list (car se-s
)))
364 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
365 (t (format t
"~22a aliased~%" (select p-names i
)))))
367 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
368 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
369 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
370 (if (/= (send self
:num-cases
) (send self
:num-included
))
371 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
372 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
376 ;;; Slot accessors and mutators
378 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
379 "Message args: (&optional new-doc)
381 Returns the DOC-STRING as supplied to m.
382 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
383 NEW-DOC. In this setting, when APPEND is T, don't replace and just
384 append NEW-DOC to DOC."
386 (when (and new-doc
(stringp new-doc
))
387 (setf (proto-slot-value 'doc
)
390 (proto-slot-value 'doc
)
393 (proto-slot-value 'doc
))
396 (defmeth regression-model-proto
:x
(&optional new-x
)
397 "Message args: (&optional new-x)
399 With no argument returns the x matrix-like as supplied to m. With an
400 argument, NEW-X sets the x matrix-like to NEW-X and recomputes the
402 (when (and new-x
(typep new-x
'matrix-like
))
403 (setf (proto-slot-value 'x
) new-x
)
404 (send self
:needs-computing t
))
405 (proto-slot-value 'x
))
407 (defmeth regression-model-proto
:y
(&optional new-y
)
408 "Message args: (&optional new-y)
410 With no argument returns the y vector-like as supplied to m. With an
411 argument, NEW-Y sets the y vector-like to NEW-Y and recomputes the
414 (typep new-y
'vector-like
))
415 (setf (proto-slot-value 'y
) new-y
) ;; fixme -- pls set slot value to a vector-like!
416 (send self
:needs-computing t
))
417 (proto-slot-value 'y
))
419 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
420 "Message args: (&optional new-intercept)
422 With no argument returns T if the model includes an intercept term,
423 nil if not. With an argument NEW-INTERCEPT the model is changed to
424 include or exclude an intercept, according to the value of
427 (setf (proto-slot-value 'intercept
) val
)
428 (send self
:needs-computing t
))
429 (proto-slot-value 'intercept
))
431 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
432 "Message args: (&optional new-w)
434 With no argument returns the weight vector-like as supplied to m; NIL
435 means an unweighted model. NEW-W sets the weights vector-like to NEW-W
436 and recomputes the estimates."
438 #|
;; probably need to use "check-type" or similar?
441 (typep new-w
'vector-like
)))
443 (setf (proto-slot-value 'weights
) new-w
)
444 (send self
:needs-computing t
))
445 (proto-slot-value 'weights
))
447 (defmeth regression-model-proto
:total-sum-of-squares
()
450 Returns the total sum of squares around the mean.
451 This is recomputed if an update is needed."
452 (if (send self
:needs-computing
)
453 (send self
:compute
))
454 (proto-slot-value 'total-sum-of-squares
))
456 (defmeth regression-model-proto
:residual-sum-of-squares
()
459 Returns the residual sum of squares for the model.
460 This is recomputed if an update is needed."
461 (if (send self
:needs-computing
)
462 (send self
:compute
))
463 (proto-slot-value 'residual-sum-of-squares
))
465 (defmeth regression-model-proto
:basis
()
468 Returns the indices of the variables used in fitting the model, in a
470 This is recomputed if an update is needed."
471 (if (send self
:needs-computing
)
472 (send self
:compute
))
473 (proto-slot-value 'basis
))
475 (defmeth regression-model-proto
:included
(&optional new-included
)
476 "Message args: (&optional new-included)
478 With no argument, NIL means a case is not used in calculating
479 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
480 of length of y of nil and t to select cases. Estimates are
485 (= (length new-included
) (send self
:num-cases
)))
487 (setf (proto-slot-value 'included
) (copy-seq new-included
))
488 (send self
:needs-computing t
))
489 (if (proto-slot-value 'included
)
490 (proto-slot-value 'included
)
491 (repeat t
(send self
:num-cases
))))
493 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
494 "Message args: (&optional (names nil set))
496 With no argument returns the predictor names. NAMES sets the names."
497 (if set
(setf (proto-slot-value 'predictor-names
) (mapcar #'string names
)))
498 (let ((p (matrix-dimension (send self
:x
) 1))
499 (p-names (proto-slot-value 'predictor-names
)))
500 (if (not (and p-names
(= (length p-names
) p
)))
501 (setf (proto-slot-value 'predictor-names
)
502 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
504 (proto-slot-value 'predictor-names
))
506 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
507 "Message args: (&optional name)
509 With no argument returns the response name. NAME sets the name."
511 (if set
(setf (proto-slot-value 'response-name
) (if name
(string name
) "Y")))
512 (proto-slot-value 'response-name
))
514 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
515 "Message args: (&optional labels)
516 With no argument returns the case-labels. LABELS sets the labels."
517 (if set
(setf (proto-slot-value 'case-labels
)
519 (mapcar #'string labels
)
520 (mapcar #'(lambda (x) (format nil
"~d" x
))
521 (iseq 0 (- (send self
:num-cases
) 1))))))
522 (proto-slot-value 'case-labels
))
526 ;;; None of these methods access any slots directly.
529 (defmeth regression-model-proto
:num-cases
()
531 Returns the number of cases in the model."
532 (nelts (send self
:y
))) ; # cases in data, must accomodate weights or masking!
534 (defmeth regression-model-proto
:num-included
()
536 Returns the number of cases used in the computations."
537 (sum (if-else (send self
:included
) 1 0)))
539 (defmeth regression-model-proto
:num-coefs
()
541 Returns the number of coefficients in the fit model (including the
542 intercept if the model includes one)."
543 (if (send self
:intercept
)
544 (+ 1 (ncols (send self
:x
)))
545 (ncols (send self
:x
))))
547 (defmeth regression-model-proto
:df
()
549 Returns the number of degrees of freedom in the model."
550 (- (send self
:num-included
) (send self
:num-coefs
)))
552 (defmeth regression-model-proto
:x-matrix
()
554 Returns the X matrix for the model, including a column of 1's, if
555 appropriate. Columns of X matrix correspond to entries in basis."
556 (let ((m (select (send self
:x
)
557 (iseq 0 (- (send self
:num-cases
) 1))
558 (send self
:basis
))))
559 (if (send self
:intercept
)
560 (bind2 (repeat 1 (send self
:num-cases
)) m
)
563 (defmeth regression-model-proto
:leverages
()
565 Returns the diagonal elements of the hat matrix."
566 (let* ((x (send self
:x-matrix
))
571 (repeat 1 (send self
:num-coefs
)))))
572 (if (send self
:weights
)
573 (m* (send self
:weights
) raw-levs
)
576 (defmeth regression-model-proto
:fit-values
()
578 Returns the fitted values for the model."
579 (m* (send self
:x-matrix
)
580 (send self
:coef-estimates
)))
582 (defmeth regression-model-proto
:raw-residuals
()
584 Returns the raw residuals for a model."
585 (v- (send self
:y
) (send self
:fit-values
)))
587 (defmeth regression-model-proto
:residuals
()
589 Returns the raw residuals for a model without weights. If the model
590 includes weights the raw residuals times the square roots of the weights
592 (let ((raw-residuals (send self
:raw-residuals
))
593 (weights (send self
:weights
)))
594 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
596 (defmeth regression-model-proto
:sum-of-squares
()
598 Returns the error sum of squares for the model."
599 (send self
:residual-sum-of-squares
))
601 (defmeth regression-model-proto
:sigma-hat
()
603 Returns the estimated standard deviation of the deviations about the
605 (let ((ss (send self
:sum-of-squares
))
606 (df (send self
:df
)))
607 (if (/= df
0) (sqrt (/ ss df
)))))
609 ;; for models without an intercept the 'usual' formula for R^2 can give
610 ;; negative results; hence the max.
611 (defmeth regression-model-proto
:r-squared
()
613 Returns the sample squared multiple correlation coefficient, R squared, for
615 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
618 (defmeth regression-model-proto
:coef-estimates
()
621 Returns the OLS (ordinary least squares) estimates of the regression
622 coefficients. Entries beyond the intercept correspond to entries in
624 (let ((x (send self
:x
)))
627 (let ((n (matrix-dimension (send self
:x
) 1))
628 (indices (flatten-list
629 (if (send self
:intercept
)
630 (cons 0 (+ 1 (send self
:basis
)))
631 (list (+ 1 (send self
:basis
))))))
633 (format t
"~%REMOVEME2: Coef-ests: ~% Sweep Matrix: ~A ~% array dim 1: ~A ~% Swept indices: ~A ~% basis: ~A"
634 x n indices
(send self
:basis
))
635 (coerce (compound-data-seq (select m
(1+ n
) indices
)) 'list
))) ;; ERROR
638 (defmeth regression-model-proto
:xtxinv
()
640 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
641 (xtxinv (send self
:x
)))
643 (defmeth regression-model-proto
:coef-standard-errors
()
645 Returns estimated standard errors of coefficients. Entries beyond the
646 intercept correspond to entries in basis."
647 (let ((s (send self
:sigma-hat
))
648 (v (map-vec #'sqrt
(diagonalf (send self
:xtxinv
)))))
651 (double (axpy s v
(make-vector (nelts v
) :type
:column
:initial-element
0d0
)))
652 (vector-like (v* (send self
:sigma-hat
) v
)))
655 (defmeth regression-model-proto
:studentized-residuals
()
657 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
658 (let ((res (send self
:residuals
))
659 (lev (send self
:leverages
))
660 (sig (send self
:sigma-hat
))
661 (inc (send self
:included
)))
663 (/ res
(* sig
(sqrt (max .00001 (- 1 lev
))))) ; vectorize max
664 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
666 (defmeth regression-model-proto
:externally-studentized-residuals
()
668 Computes the externally studentized residuals."
669 (let* ((res (send self
:studentized-residuals
))
670 (df (send self
:df
)))
671 (if-else (send self
:included
)
672 (* res
(sqrt (/ (- df
1) (- df
(v* res res
)))))
675 (defmeth regression-model-proto
:cooks-distances
()
677 Computes Cook's distances."
678 (let ((lev (send self
:leverages
))
679 (res (/ (v* (send self
:studentized-residuals
)
680 (send self
:studentized-residuals
))
681 (send self
:num-coefs
))))
682 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
685 (defun plot-points (x y
&rest args
)
687 (error "Graphics not implemented yet."))
692 ;; Can not plot points yet!!
693 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
694 "Message args: (&optional x-values)
695 Opens a window with a plot of the residuals. If X-VALUES are not supplied
696 the fitted values are used. The plot can be linked to other plots with the
697 link-views function. Returns a plot object."
698 (plot-points (if x-values x-values
(send self
:fit-values
))
699 (send self
:residuals
)
700 :title
"Residual Plot"
701 :point-labels
(send self
:case-labels
)))
705 (defmeth regression-model-proto
:plot-bayes-residuals
707 "Message args: (&optional x-values)
709 Opens a window with a plot of the standardized residuals and two
710 standard error bars for the posterior distribution of the actual
711 deviations from the line. See Chaloner and Brant. If X-VALUES are not
712 supplied the fitted values are used. The plot can be linked to other
713 plots with the link-views function. Returns a plot object."
715 (let* ((r (/ (send self
:residuals
)
716 (send self
:sigma-hat
)))
717 (d (* 2 (sqrt (send self
:leverages
))))
720 (x-values (if x-values x-values
(send self
:fit-values
)))
721 (p (plot-points x-values r
722 :title
"Bayes Residual Plot"
723 :point-labels
(send self
:case-labels
))))
724 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
725 x-values low x-values high
)
726 (send p
:adjust-to-data
)
733 (defun print-lm (lm-obj)
737 ;; EVIL LOGIC! Just to store for now.
739 (n (length (residuals lm-obj
)))
740 (w (if (weights lm-obj
)
743 (r (if (weights lm-obj
)
745 (v.
* (residuals lm-obj
)
746 (mapcar #'sqrt
(weights lm-obj
)))))
747 (rss (sum (v.
* r r
)))
748 (resvar (/ rss
(- n p
)))
749 ;; then answer, to be encapsulated in a struct/class
751 (aliased (is.na
(coef lm-obj
)))
753 (df (list 0 n
(length aliased
)))
754 (coefficients (list 'NA
0d0
4d0
))o
755 (sigma (sqrt resvar
))
757 (adj.r.squared
0d0
)))
761 (let ((n (nrows (qr lm-obj
)))
766 (lm (transpose *xv
*) *y2
*)
768 (princ "Linear Models Code setup")