3 ;;; Copyright (c) 2005--2007, 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.
16 ;;;; Incorporates modifications suggested by Sandy Weisberg.
21 (defpackage :lisp-stat-regression-linear
23 :lisp-stat-object-system
25 :lisp-stat-compound-data
29 :lisp-stat-descriptive-statistics
)
30 (:shadowing-import-from
:lisp-stat-object-system
31 slot-value call-method call-next-method
)
32 (:shadowing-import-from
:lisp-stat-math
33 expt
+ -
* / ** mod rem abs
1+ 1- log exp sqrt sin cos tan
34 asin acos atan sinh cosh tanh asinh acosh atanh float random
35 truncate floor ceiling round minusp zerop plusp evenp oddp
36 < <= = /= >= > ;; complex
37 conjugate realpart imagpart phase
38 min max logand logior logxor lognot ffloor fceiling
39 ftruncate fround signum cis
)
40 (:export regression-model regression-model-proto x y intercept sweep-matrix
41 basis weights included total-sum-of-squares residual-sum-of-squares
42 predictor-names response-name case-labels
))
44 (in-package :lisp-stat-regression-linear
)
46 ;;; Regresion Model Prototype
49 ;; The general strategy behind the fitting of models using prototypes
50 ;; is that we need to think about want the actual fits are, and then
51 ;; the fits can be used to recompute as components are changes. One
52 ;; catch here is that we'd like some notion of trace-ability, in
53 ;; particular, there is not necessarily a fixed way to take care of the
54 ;; audit trail. save-nd-die might be a means of recording the final
55 ;; approach, but we are challenged by the problem of using advice and
56 ;; other such features to capture stages and steps that are considered
57 ;; along the goals of estimating a model.
59 (defvar regression-model-proto nil
60 "Prototype for all regression model instances.")
61 (defproto regression-model-proto
62 '(x y intercept sweep-matrix basis weights
65 residual-sum-of-squares
72 "Normal Linear Regression Model")
74 (defun regression-model (x y
&key
78 (included (repeat t
(length y
)))
82 (doc "Undocumented Regression Model Instance")
84 "Args: (x y &key (intercept T) (print T) (weights nil)
85 included predictor-names response-name case-labels)
86 X - list of independent variables or X matrix
87 Y - dependent variable.
88 INTERCEPT - T to include (default), NIL for no intercept
89 PRINT - if not NIL print summary information
90 WEIGHTS - if supplied should be the same length as Y; error
92 assumed to be inversely proportional to WEIGHTS
93 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
94 - sequences of strings or symbols.
95 INCLUDED - if supplied should be the same length as Y, with
96 elements nil to skip a in computing estimates (but not
97 in residual analysis).
98 Returns a regression model object. To examine the model further assign the
99 result to a variable and send it messages.
100 Example (data are in file absorbtion.lsp in the sample data directory):
101 (def m (regression-model (list iron aluminum) absorbtion))
102 (send m :help) (send m :plot-residuals)"
105 ((typep x
'vector
) (list x
))
107 (numberp (car x
))) (list x
))
109 (m (send regression-model-proto
:new
)))
112 (send m
:x
(if (matrixp x
) x
(apply #'bind-columns x
)))
114 (send m
:intercept intercept
)
115 (send m
:weights weights
)
116 (send m
:included included
)
117 (send m
:predictor-names predictor-names
)
118 (send m
:response-name response-name
)
119 (send m
:case-labels case-labels
)
123 (format t
"~S~%" (send m
:doc
))
124 (format t
"X: ~S~%" (send m
:x
))
125 (format t
"Y: ~S~%" (send m
:y
))))
126 (if print
(send m
:display
))
129 (defmeth regression-model-proto
:isnew
()
130 (send self
:needs-computing t
))
132 (defmeth regression-model-proto
:save
()
134 Returns an expression that will reconstruct the regression model."
135 `(regression-model ',(send self
:x
)
137 :intercept
',(send self
:intercept
)
138 :weights
',(send self
:weights
)
139 :included
',(send self
:included
)
140 :predictor-names
',(send self
:predictor-names
)
141 :response-name
',(send self
:response-name
)
142 :case-labels
',(send self
:case-labels
)))
144 ;;; Computing and Display Methods
146 (defmeth regression-model-proto
:compute
()
148 Recomputes the estimates. For internal use by other messages"
149 (let* ((included (if-else (send self
:included
) 1 0))
152 (intercept (send self
:intercept
))
153 (weights (send self
:weights
))
154 (w (if weights
(* included weights
) included
))
155 (m (make-sweep-matrix x y w
)) ;;; ERROR HERE
156 (n (array-dimension x
1))
157 (p (- (array-dimension m
0) 1))
159 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation
(column-list x
)))))
160 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
163 (sweep-operator m
(iseq 1 n
) tol
)
164 (sweep-operator m
(iseq 0 n
) (cons 0.0 tol
)))))
166 "~%REMOVEME: regr-mdl-prto :compute =~A~%~A~%~A~%~A~%~A~%"
167 sweep-result x y m tss
)
168 (setf (slot-value 'sweep-matrix
) (first sweep-result
))
169 (setf (slot-value 'total-sum-of-squares
) tss
)
170 (setf (slot-value 'residual-sum-of-squares
)
171 (aref (first sweep-result
) p p
))
172 (setf (slot-value 'basis
)
173 (let ((b (remove 0 (second sweep-result
))))
174 (if b
(- (reduce #'-
(reverse b
)) 1)
175 (error "no columns could be swept"))))))
177 (defmeth regression-model-proto
:needs-computing
(&optional set
)
178 "Message args: ( &optional set )
180 If value given, sets the flag for whether (re)computation is needed to
181 update the model fits."
183 (if set
(setf (slot-value 'sweep-matrix
) nil
))
184 (null (slot-value 'sweep-matrix
)))
186 (defmeth regression-model-proto
:display
()
189 Prints the least squares regression summary. Variables not used in the fit
190 are marked as aliased."
191 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
192 (se-s (send self
:coef-standard-errors
))
194 (p-names (send self
:predictor-names
)))
195 (if (send self
:weights
)
196 (format t
"~%Weighted Least Squares Estimates:~2%")
197 (format t
"~%Least Squares Estimates:~2%"))
198 (when (send self
:intercept
)
199 (format t
"Constant ~10f ~A~%"
200 (car coefs
) (list (car se-s
)))
201 (setf coefs
(cdr coefs
))
202 (setf se-s
(cdr se-s
)))
203 (dotimes (i (array-dimension x
1))
205 ((member i
(send self
:basis
))
206 (format t
"~22a ~10f ~A~%"
207 (select p-names i
) (car coefs
) (list (car se-s
)))
208 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
209 (t (format t
"~22a aliased~%" (select p-names i
)))))
211 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
212 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
213 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
214 (if (/= (send self
:num-cases
) (send self
:num-included
))
215 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
216 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
219 ;;; Slot accessors and mutators
221 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
222 "Message args: (&optional new-doc)
224 Returns the DOC-STRING as supplied to m.
225 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
226 NEW-DOC. In this setting, when APPEND is T, append NEW-DOC to DOC
227 rather than doing replacement."
229 (when (and new-doc
(stringp new-doc
))
230 (setf (slot-value 'doc
)
239 (defmeth regression-model-proto
:x
(&optional new-x
)
240 "Message args: (&optional new-x)
242 With no argument returns the x matrix as supplied to m. With an
243 argument, NEW-X sets the x matrix to NEW-X and recomputes the
245 (when (and new-x
(matrixp new-x
))
246 (setf (slot-value 'x
) new-x
)
247 (send self
:needs-computing t
))
250 (defmeth regression-model-proto
:y
(&optional new-y
)
251 "Message args: (&optional new-y)
253 With no argument returns the y sequence as supplied to m. With an
254 argument, NEW-Y sets the y sequence to NEW-Y and recomputes the
258 (typep new-y
'sequence
)))
259 (setf (slot-value 'y
) new-y
)
260 (send self
:needs-computing t
))
263 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
264 "Message args: (&optional new-intercept)
266 With no argument returns T if the model includes an intercept term,
267 nil if not. With an argument NEW-INTERCEPT the model is changed to
268 include or exclude an intercept, according to the value of
271 (setf (slot-value 'intercept
) val
)
272 (send self
:needs-computing t
))
273 (slot-value 'intercept
))
275 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
276 "Message args: (&optional new-w)
278 With no argument returns the weight sequence as supplied to m; NIL
279 means an unweighted model. NEW-W sets the weights sequence to NEW-W
280 and recomputes the estimates."
282 (setf (slot-value 'weights
) new-w
)
283 (send self
:needs-computing t
))
284 (slot-value 'weights
))
286 (defmeth regression-model-proto
:total-sum-of-squares
()
289 Returns the total sum of squares around the mean."
290 (if (send self
:needs-computing
) (send self
:compute
))
291 (slot-value 'total-sum-of-squares
))
293 (defmeth regression-model-proto
:residual-sum-of-squares
()
296 Returns the residual sum of squares for the model."
297 (if (send self
:needs-computing
) (send self
:compute
))
298 (slot-value 'residual-sum-of-squares
))
300 (defmeth regression-model-proto
:basis
()
303 Returns the indices of the variables used in fitting the model, in a
305 (if (send self
:needs-computing
)
306 (send self
:compute
))
307 (if (typep (slot-value 'basis
) 'sequence
)
309 (list (slot-value 'basis
))))
312 (defmeth regression-model-proto
:sweep-matrix
()
315 Returns the swept sweep matrix. For internal use"
316 (if (send self
:needs-computing
)
317 (send self
:compute
))
318 (slot-value 'sweep-matrix
))
320 (defmeth regression-model-proto
:included
(&optional new-included
)
321 "Message args: (&optional new-included)
323 With no argument, NIL means a case is not used in calculating
324 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
325 of length of y of nil and t to select cases. Estimates are
327 (when (and new-included
328 (= (length new-included
) (send self
:num-cases
)))
329 (setf (slot-value 'included
) (copy-seq new-included
))
330 (send self
:needs-computing t
))
331 (if (slot-value 'included
)
332 (slot-value 'included
)
333 (repeat t
(send self
:num-cases
))))
335 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
336 "Message args: (&optional (names nil set))
338 With no argument returns the predictor names. NAMES sets the names."
339 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
340 (let ((p (array-dimension (send self
:x
) 1))
341 (p-names (slot-value 'predictor-names
)))
342 (if (not (and p-names
(= (length p-names
) p
)))
343 (setf (slot-value 'predictor-names
)
344 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
346 (slot-value 'predictor-names
))
348 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
349 "Message args: (&optional name)
351 With no argument returns the response name. NAME sets the name."
353 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
354 (slot-value 'response-name
))
356 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
357 "Message args: (&optional labels)
358 With no argument returns the case-labels. LABELS sets the labels."
359 (if set
(setf (slot-value 'case-labels
)
361 (mapcar #'string labels
)
362 (mapcar #'(lambda (x) (format nil
"~d" x
))
363 (iseq 0 (- (send self
:num-cases
) 1))))))
364 (slot-value 'case-labels
))
368 ;;; None of these methods access any slots directly.
371 (defmeth regression-model-proto
:num-cases
()
373 Returns the number of cases in the model."
374 (length (send self
:y
)))
376 (defmeth regression-model-proto
:num-included
()
378 Returns the number of cases used in the computations."
379 (sum (if-else (send self
:included
) 1 0)))
381 (defmeth regression-model-proto
:num-coefs
()
383 Returns the number of coefficients in the fit model (including the
384 intercept if the model includes one)."
385 (if (send self
:intercept
)
386 (+ 1 (length (send self
:basis
)))
387 (length (send self
:basis
))))
389 (defmeth regression-model-proto
:df
()
391 Returns the number of degrees of freedom in the model."
392 (- (send self
:num-included
) (send self
:num-coefs
)))
394 (defmeth regression-model-proto
:x-matrix
()
396 Returns the X matrix for the model, including a column of 1's, if
397 appropriate. Columns of X matrix correspond to entries in basis."
398 (let ((m (select (send self
:x
)
399 (iseq 0 (- (send self
:num-cases
) 1))
400 (send self
:basis
))))
401 (if (send self
:intercept
)
402 (bind-columns (repeat 1 (send self
:num-cases
)) m
)
405 (defmeth regression-model-proto
:leverages
()
407 Returns the diagonal elements of the hat matrix."
408 (let* ((weights (send self
:weights
))
409 (x (send self
:x-matrix
))
411 (matmult (* (matmult x
(send self
:xtxinv
)) x
)
412 (repeat 1 (send self
:num-coefs
)))))
413 (if weights
(* weights raw-levs
) raw-levs
)))
415 (defmeth regression-model-proto
:fit-values
()
417 Returns the fitted values for the model."
418 (matmult (send self
:x-matrix
) (send self
:coef-estimates
)))
420 (defmeth regression-model-proto
:raw-residuals
()
422 Returns the raw residuals for a model."
423 (- (send self
:y
) (send self
:fit-values
)))
425 (defmeth regression-model-proto
:residuals
()
427 Returns the raw residuals for a model without weights. If the model
428 includes weights the raw residuals times the square roots of the weights
430 (let ((raw-residuals (send self
:raw-residuals
))
431 (weights (send self
:weights
)))
432 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
434 (defmeth regression-model-proto
:sum-of-squares
()
436 Returns the error sum of squares for the model."
437 (send self
:residual-sum-of-squares
))
439 (defmeth regression-model-proto
:sigma-hat
()
441 Returns the estimated standard deviation of the deviations about the
443 (let ((ss (send self
:sum-of-squares
))
444 (df (send self
:df
)))
445 (if (/= df
0) (sqrt (/ ss df
)))))
447 ;; for models without an intercept the 'usual' formula for R^2 can give
448 ;; negative results; hence the max.
449 (defmeth regression-model-proto
:r-squared
()
451 Returns the sample squared multiple correlation coefficient, R squared, for
453 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
456 (defmeth regression-model-proto
:coef-estimates
()
459 Returns the OLS (ordinary least squares) estimates of the regression
460 coefficients. Entries beyond the intercept correspond to entries in
462 (let ((n (array-dimension (send self
:x
) 1))
463 (indices (flatten-list
464 (if (send self
:intercept
)
465 (list 0 (+ 1 (send self
:basis
))) ;; was cons -- why?
466 (list (+ 1 (send self
:basis
))))))
467 (m (send self
:sweep-matrix
)))
468 (format t
"~%REMOVEME2: Coef-ests: ~A ~% ~A ~% ~A ~% ~A"
469 m n indices
(send self
:basis
))
470 (coerce (compound-data-seq (select m
(+ 1 n
) indices
)) 'list
)))
472 (defmeth regression-model-proto
:xtxinv
()
474 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
475 (let ((indices (if (send self
:intercept
)
476 (cons 0 (1+ (send self
:basis
)))
477 (1+ (send self
:basis
)))))
478 (select (send self
:sweep-matrix
) indices indices
)))
480 (defmeth regression-model-proto
:coef-standard-errors
()
482 Returns estimated standard errors of coefficients. Entries beyond the
483 intercept correspond to entries in basis."
484 (let ((s (send self
:sigma-hat
)))
485 (if s
(* (send self
:sigma-hat
) (sqrt (diagonal (send self
:xtxinv
)))))))
487 (defmeth regression-model-proto
:studentized-residuals
()
489 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
490 (let ((res (send self
:residuals
))
491 (lev (send self
:leverages
))
492 (sig (send self
:sigma-hat
))
493 (inc (send self
:included
)))
495 (/ res
(* sig
(sqrt (pmax .00001 (- 1 lev
)))))
496 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
498 (defmeth regression-model-proto
:externally-studentized-residuals
()
500 Computes the externally studentized residuals."
501 (let* ((res (send self
:studentized-residuals
))
502 (df (send self
:df
)))
503 (if-else (send self
:included
)
504 (* res
(sqrt (/ (- df
1) (- df
(^ res
2)))))
507 (defmeth regression-model-proto
:cooks-distances
()
509 Computes Cook's distances."
510 (let ((lev (send self
:leverages
))
511 (res (/ (^
(send self
:studentized-residuals
) 2)
512 (send self
:num-coefs
))))
513 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
516 (defun plot-points (x y
&rest args
)
518 (declare (ignore x y args
))
519 (error "Graphics not implemented yet."))
521 ;; Can not plot points yet!!
522 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
523 "Message args: (&optional x-values)
524 Opens a window with a plot of the residuals. If X-VALUES are not supplied
525 the fitted values are used. The plot can be linked to other plots with the
526 link-views function. Returns a plot object."
527 (plot-points (if x-values x-values
(send self
:fit-values
))
528 (send self
:residuals
)
529 :title
"Residual Plot"
530 :point-labels
(send self
:case-labels
)))
532 (defmeth regression-model-proto
:plot-bayes-residuals
534 "Message args: (&optional x-values)
536 Opens a window with a plot of the standardized residuals and two
537 standard error bars for the posterior distribution of the actual
538 deviations from the line. See Chaloner and Brant. If X-VALUES are not
539 supplied the fitted values are used. The plot can be linked to other
540 plots with the link-views function. Returns a plot object."
542 (let* ((r (/ (send self
:residuals
)
543 (send self
:sigma-hat
)))
544 (d (* 2 (sqrt (send self
:leverages
))))
547 (x-values (if x-values x-values
(send self
:fit-values
)))
548 (p (plot-points x-values r
549 :title
"Bayes Residual Plot"
550 :point-labels
(send self
:case-labels
))))
551 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
552 x-values low x-values high
)
553 (send p
:adjust-to-data
)