regression starting to move over to CLOS, giving up on LSOS for now.
[CommonLispStat.git] / src / stat-models / regression.lisp
blobb54046c8af540d6fc6293fab1d8c3ea1367b3e03
1 ;;; -*- mode: lisp -*-
2 ;;;
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
6 ;;; Common Lisp.
8 ;;;; Originally from:
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.
14 ;;;;
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"
35 ;; computation.
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)
47 (;; data/design/state
49 :initform nil
50 :initarg :y
51 :accessor response-variable
52 :type vector-like)
54 :initform nil
55 :initarg :x
56 :accessor design-matrix
57 :type matrix-like)
58 (interceptp
59 :initform nil
60 :initarg :interceptp
61 :accessor interceptp
62 :type boolean)
64 ;; metadata
65 (covariate-names
66 :initform nil
67 :initarg :covariate-names
68 :accessor covariate-names
69 :type list)
70 (response-name
71 :initform nil
72 :initarg :response-name
73 :accessor response-name
74 :type list)
75 (case-labels
76 :initform nil
77 :initarg :case-labels
78 :accessor case-labels
79 :type list)
80 (doc-string
81 :initform ""
82 :initarg :docs
83 :accessor doc-string
84 :type string))
85 (:documentation "Normal Linear Regression Model with CLOS.
86 Historical design based on LispStat."))
89 (defclass regression-model-fit-class ()
90 (;; data/design/state
91 (data-model
92 :initform nil
93 :initarg :data-model
94 :accessor data-model
95 :type regression-model-class)
96 (needs-computing
97 :initform T
98 :initarg :needs-computing
99 :accessor needs-computing)
102 (included
103 :initform nil
104 :initarg :included
105 :accessor included
106 :type matrix-like)
107 (weights
108 :initform nil
109 :initarg :weights
110 :accessor weights
111 :type matrix-like)
113 (weights-types
114 :initform nil
115 :initarg :weight-types
116 :accessor weight-types
117 :type matrix-like)
119 ;; computational artifacts
121 (basis
122 :initform nil
123 :accessor basis
124 :type matrix-like)
125 (estimates
126 :initform nil
127 :initarg :estimates
128 :accessor estimates
129 :type vector-like)
130 (estimates-covariance-matrix
131 :initform nil
132 :initarg :estimates-covariance-matrix
133 :accessor covariation-matrix
134 :type matrix-like)
135 (total-sum-of-squares
136 :initform 0d0
137 :accessor tss
138 :type number)
139 (residual-sum-of-squares
140 :initform 0d0
141 :accessor rss
142 :type number)
144 (doc-string
145 :initform ""
146 :initarg :doc
147 :accessor doc-string
148 :type string))
149 (:documentation "Normal Linear Regression Model _FIT_ through CLOS."))
151 ;;;;;;;; Helper functions
153 (defun xtxinv (x)
154 "In: X Out: (XtX)^-1
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.
160 <example>
161 (let ((m1 (rand 7 5)))
162 (xtxinv m1))
163 </example>"
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
170 ;; LAPACK solvers?
171 (defun lm (x y &key (intercept T) rcond)
172 "fit the linear model:
173 y = x \beta + e
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?
184 (assert
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)
189 x :by :column)
190 x)))
191 (let ((betahat (gelsy (m* (transpose x1) x1)
192 (m* (transpose x1) y)
193 (if rcond rcond
194 (* (coerce (expt 2 -52) 'double-float)
195 (max (nrows x1)
196 (ncols y))))))
197 (betahat1 (gelsy x1
199 (if rcond rcond
200 (* (coerce (expt 2 -52) 'double-float)
201 (max (nrows x1)
202 (ncols y)))))))
203 ;; need computation for SEs,
204 (format t "")
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
223 variances are
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
234 :y y
235 :x x
236 :interceptp intercept
237 :case-labels case-labels
238 :covariate-names predictor-names
239 :response-name response-name
240 :docs doc )))
241 newmodel))
243 (defun fit-model (model &key (included T) (wgts nil) (docs "No Docs"))
244 (let ((result (make-instance 'regression-model-fit-class
245 :data-model model
246 :needs-computing T
247 :included included
248 :weights wgts
249 :estimates (first (lm (design-matrix model)
250 (response-variable model)
251 :intercept (interceptp model)))
252 :estimates-covariance-matrix (xtxinv (design-matrix model))
253 :doc docs)))
254 result))
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 ()
266 "Message args: ()
267 Returns an expression that will reconstruct the regression model."
268 `(regression-model ',(send self :x)
269 ',(send self :y)
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
279 ;; [X|Y]t [X|Y]
280 ;; = XtX XtY
281 ;; YtX YtY
282 ;; so with (= (dim X) (list n p))
283 ;; we end up with p x p p x 1
284 ;; 1 x p 1 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 ()
299 "Message args: ()
300 Recomputes the estimates. For internal use by other messages"
301 (let* ((included (if-else (send self :included) 1d0 0d0))
302 (x (send self :x))
303 (y (send self :y))
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))
308 (p (if intercept
309 (1- (matrix-dimension x 1))
310 (matrix-dimension x 1))) ;; remove intercept from # params -- right?
311 (tss 0)
312 (res (make-vector (nrows x) :type :column :initial-element 0d0)) ; (compute-residuals y yhat)
313 (tol 0.000001
314 ;; (* 0.001 (reduce #'* (mapcar #'standard-deviation (list-of-columns x))))
316 (format t
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."
335 (send self :nop)
336 (if set (setf (proto-slot-value 'betahat) nil))
337 (null (proto-slot-value 'betahat)))
339 (defmeth regression-model-proto :display ()
340 "Message args: ()
341 Prints the least squares regression summary. Variables not used in the fit
342 are marked as aliased."
343 (send self :x)
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))
349 (x (send self :x))
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))
360 (cond
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)))))
366 (format t "~%")
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))
373 (format t "~%")))
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."
385 (send self :nop)
386 (when (and new-doc (stringp new-doc))
387 (setf (proto-slot-value 'doc)
388 (if append
389 (concatenate 'string
390 (proto-slot-value 'doc)
391 new-doc)
392 new-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
401 estimates."
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
412 estimates."
413 (when (and new-y
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
425 NEW-INTERCEPT."
426 (when set
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."
437 (when set
438 #| ;; probably need to use "check-type" or similar?
439 (and set nil
440 (or (= new-w nil)
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 ()
448 "Message args: ()
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 ()
457 "Message args: ()
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 ()
466 "Message args: ()
468 Returns the indices of the variables used in fitting the model, in a
469 sequence.
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
481 recomputed."
482 (when new-included
484 (and new-included
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))
503 (iseq 0 (- p 1))))))
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."
510 (send self :nop)
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)
518 (if 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))
525 ;;; Other Methods
526 ;;; None of these methods access any slots directly.
529 (defmeth regression-model-proto :num-cases ()
530 "Message args: ()
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 ()
535 "Message args: ()
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 ()
540 "Message args: ()
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 ()
548 "Message args: ()
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 ()
553 "Message args: ()
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)
561 m)))
563 (defmeth regression-model-proto :leverages ()
564 "Message args: ()
565 Returns the diagonal elements of the hat matrix."
566 (let* ((x (send self :x-matrix))
567 (raw-levs
568 (m* (m* (m* x
569 (send self :xtxinv))
571 (repeat 1 (send self :num-coefs)))))
572 (if (send self :weights)
573 (m* (send self :weights) raw-levs)
574 raw-levs)))
576 (defmeth regression-model-proto :fit-values ()
577 "Message args: ()
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 ()
583 "Message args: ()
584 Returns the raw residuals for a model."
585 (v- (send self :y) (send self :fit-values)))
587 (defmeth regression-model-proto :residuals ()
588 "Message args: ()
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
591 are returned."
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 ()
597 "Message args: ()
598 Returns the error sum of squares for the model."
599 (send self :residual-sum-of-squares))
601 (defmeth regression-model-proto :sigma-hat ()
602 "Message args: ()
603 Returns the estimated standard deviation of the deviations about the
604 regression line."
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 ()
612 "Message args: ()
613 Returns the sample squared multiple correlation coefficient, R squared, for
614 the regression."
615 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
618 (defmeth regression-model-proto :coef-estimates ()
619 "Message args: ()
621 Returns the OLS (ordinary least squares) estimates of the regression
622 coefficients. Entries beyond the intercept correspond to entries in
623 basis."
624 (let ((x (send self :x)))
625 (princ 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))))))
632 (x (send self :x)))
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 ()
639 "Message args: ()
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 ()
644 "Message args: ()
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)))))
649 (if s
650 (etypecase s
651 (double (axpy s v (make-vector (nelts v) :type :column :initial-element 0d0)))
652 (vector-like (v* (send self :sigma-hat) v)))
653 v)))
655 (defmeth regression-model-proto :studentized-residuals ()
656 "Message args: ()
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)))
662 (if-else inc
663 (/ res (* sig (sqrt (max .00001 (- 1 lev))))) ; vectorize max
664 (/ res (* sig (sqrt (+ 1 lev)))))))
666 (defmeth regression-model-proto :externally-studentized-residuals ()
667 "Message args: ()
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)))))
673 res)))
675 (defmeth regression-model-proto :cooks-distances ()
676 "Message args: ()
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)
686 "need to fix."
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
706 (&optional x-values)
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))))
718 (low (- r d))
719 (high (+ r d))
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)
730 ;;;; Other code
733 (defun print-lm (lm-obj)
734 "transcribed from R"
735 (p (rank lm-obj)
736 (when (= p 0)
737 ;; EVIL LOGIC! Just to store for now.
738 (let ()
739 (n (length (residuals lm-obj)))
740 (w (if (weights lm-obj)
741 (weights lm-obj)
742 (ones n 1)))
743 (r (if (weights lm-obj)
744 (residuals 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
750 ;; instance,
751 (aliased (is.na (coef lm-obj)))
752 (residuals r)
753 (df (list 0 n (length aliased)))
754 (coefficients (list 'NA 0d0 4d0))o
755 (sigma (sqrt resvar))
756 (r.squared 0d0)
757 (adj.r.squared 0d0)))
759 ;;otherwise...
760 (when (not (= p 0))
761 (let ((n (nrows (qr lm-obj)))
762 (rdf (- n p))
763 ))))
765 (lm *xv+1* *y2*)
766 (lm (transpose *xv*) *y2*)
768 (princ "Linear Models Code setup")