3 ;;; Copyright (c) 2005--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.
19 (defpackage :lisp-stat-regression-linear
21 :lisp-stat-object-system
23 :lisp-stat-compound-data
27 :lisp-stat-descriptive-statistics
)
28 (:shadowing-import-from
:lisp-stat-object-system
29 slot-value call-method call-next-method
)
30 (:shadowing-import-from
:lisp-stat-math
31 expt
+ -
* / ** mod rem abs
1+ 1- log exp sqrt sin cos tan
32 asin acos atan sinh cosh tanh asinh acosh atanh float random
33 truncate floor ceiling round minusp zerop plusp evenp oddp
34 < <= = /= >= > ;; complex
35 conjugate realpart imagpart phase
36 min max logand logior logxor lognot ffloor fceiling
37 ftruncate fround signum cis
)
38 (:export regression-model regression-model-proto x y intercept sweep-matrix
39 basis weights included total-sum-of-squares residual-sum-of-squares
40 predictor-names response-name case-labels
))
42 (in-package :lisp-stat-regression-linear
)
44 ;;; Regresion Model Prototype
47 ;; The general strategy behind the fitting of models using prototypes
48 ;; is that we need to think about want the actual fits are, and then
49 ;; the fits can be used to recompute as components are changes. One
50 ;; catch here is that we'd like some notion of trace-ability, in
51 ;; particular, there is not necessarily a fixed way to take care of the
52 ;; audit trail. save-nd-die might be a means of recording the final
53 ;; approach, but we are challenged by the problem of using advice and
54 ;; other such features to capture stages and steps that are considered
55 ;; along the goals of estimating a model.
57 (defvar regression-model-proto nil
58 "Prototype for all regression model instances.")
59 (defproto regression-model-proto
60 '(x y intercept sweep-matrix basis weights
63 residual-sum-of-squares
70 "Normal Linear Regression Model")
72 (defun regression-model (x y
&key
76 (included (repeat t
(length y
)))
80 (doc "Undocumented Regression Model Instance")
82 "Args: (x y &key (intercept T) (print T) (weights nil)
83 included predictor-names response-name case-labels)
84 X - list of independent variables or X matrix
85 Y - dependent variable.
86 INTERCEPT - T to include (default), NIL for no intercept
87 PRINT - if not NIL print summary information
88 WEIGHTS - if supplied should be the same length as Y; error
90 assumed to be inversely proportional to WEIGHTS
91 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
92 - sequences of strings or symbols.
93 INCLUDED - if supplied should be the same length as Y, with
94 elements nil to skip a in computing estimates (but not
95 in residual analysis).
96 Returns a regression model object. To examine the model further assign the
97 result to a variable and send it messages.
98 Example (data are in file absorbtion.lsp in the sample data directory):
99 (def m (regression-model (list iron aluminum) absorbtion))
100 (send m :help) (send m :plot-residuals)"
103 ((typep x
'vector
) (list x
))
105 (numberp (car x
))) (list x
))
107 (m (send regression-model-proto
:new
)))
110 (send m
:x
(if (matrixp x
) x
(apply #'bind-columns x
)))
112 (send m
:intercept intercept
)
113 (send m
:weights weights
)
114 (send m
:included included
)
115 (send m
:predictor-names predictor-names
)
116 (send m
:response-name response-name
)
117 (send m
:case-labels case-labels
)
121 (format t
"~S~%" (send m
:doc
))
122 (format t
"X: ~S~%" (send m
:x
))
123 (format t
"Y: ~S~%" (send m
:y
))))
124 (if print
(send m
:display
))
127 (defmeth regression-model-proto
:isnew
()
128 (send self
:needs-computing t
))
130 (defmeth regression-model-proto
:save
()
132 Returns an expression that will reconstruct the regression model."
133 `(regression-model ',(send self
:x
)
135 :intercept
',(send self
:intercept
)
136 :weights
',(send self
:weights
)
137 :included
',(send self
:included
)
138 :predictor-names
',(send self
:predictor-names
)
139 :response-name
',(send self
:response-name
)
140 :case-labels
',(send self
:case-labels
)))
142 ;;; Computing and Display Methods
144 (defmeth regression-model-proto
:compute
()
146 Recomputes the estimates. For internal use by other messages"
147 (let* ((included (if-else (send self
:included
) 1 0))
150 (intercept (send self
:intercept
))
151 (weights (send self
:weights
))
152 (w (if weights
(* included weights
) included
))
153 (m (make-sweep-matrix x y w
)) ;;; ERROR HERE
154 (n (array-dimension x
1))
155 (p (- (array-dimension m
0) 1))
157 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation
(column-list x
)))))
158 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
161 (sweep-operator m
(iseq 1 n
) tol
)
162 (sweep-operator m
(iseq 0 n
) (cons 0.0 tol
)))))
164 "~%REMOVEME: regr-mdl-prto :compute =~A~%~A~%~A~%~A~%~A~%"
165 sweep-result x y m tss
)
166 (setf (slot-value 'sweep-matrix
) (first sweep-result
))
167 (setf (slot-value 'total-sum-of-squares
) tss
)
168 (setf (slot-value 'residual-sum-of-squares
)
169 (aref (first sweep-result
) p p
))
170 (setf (slot-value 'basis
)
171 (let ((b (remove 0 (second sweep-result
))))
172 (if b
(- (reduce #'-
(reverse b
)) 1)
173 (error "no columns could be swept"))))))
175 (defmeth regression-model-proto
:needs-computing
(&optional set
)
176 "Message args: ( &optional set )
178 If value given, sets the flag for whether (re)computation is needed to
179 update the model fits."
181 (if set
(setf (slot-value 'sweep-matrix
) nil
))
182 (null (slot-value 'sweep-matrix
)))
184 (defmeth regression-model-proto
:display
()
187 Prints the least squares regression summary. Variables not used in the fit
188 are marked as aliased."
189 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
190 (se-s (send self
:coef-standard-errors
))
192 (p-names (send self
:predictor-names
)))
193 (if (send self
:weights
)
194 (format t
"~%Weighted Least Squares Estimates:~2%")
195 (format t
"~%Least Squares Estimates:~2%"))
196 (when (send self
:intercept
)
197 (format t
"Constant ~10f ~A~%"
198 (car coefs
) (list (car se-s
)))
199 (setf coefs
(cdr coefs
))
200 (setf se-s
(cdr se-s
)))
201 (dotimes (i (array-dimension x
1))
203 ((member i
(send self
:basis
))
204 (format t
"~22a ~10f ~A~%"
205 (select p-names i
) (car coefs
) (list (car se-s
)))
206 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
207 (t (format t
"~22a aliased~%" (select p-names i
)))))
209 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
210 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
211 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
212 (if (/= (send self
:num-cases
) (send self
:num-included
))
213 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
214 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
217 ;;; Slot accessors and mutators
219 (defmeth regression-model-proto
:doc
(&optional new-doc append
)
220 "Message args: (&optional new-doc)
222 Returns the DOC-STRING as supplied to m.
223 Additionally, with an argument NEW-DOC, sets the DOC-STRING to
224 NEW-DOC. In this setting, when APPEND is T, append NEW-DOC to DOC
225 rather than doing replacement."
227 (when (and new-doc
(stringp new-doc
))
228 (setf (slot-value 'doc
)
237 (defmeth regression-model-proto
:x
(&optional new-x
)
238 "Message args: (&optional new-x)
240 With no argument returns the x matrix as supplied to m. With an
241 argument, NEW-X sets the x matrix to NEW-X and recomputes the
243 (when (and new-x
(matrixp new-x
))
244 (setf (slot-value 'x
) new-x
)
245 (send self
:needs-computing t
))
248 (defmeth regression-model-proto
:y
(&optional new-y
)
249 "Message args: (&optional new-y)
251 With no argument returns the y sequence as supplied to m. With an
252 argument, NEW-Y sets the y sequence to NEW-Y and recomputes the
256 (typep new-y
'sequence
)))
257 (setf (slot-value 'y
) new-y
)
258 (send self
:needs-computing t
))
261 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
262 "Message args: (&optional new-intercept)
264 With no argument returns T if the model includes an intercept term,
265 nil if not. With an argument NEW-INTERCEPT the model is changed to
266 include or exclude an intercept, according to the value of
269 (setf (slot-value 'intercept
) val
)
270 (send self
:needs-computing t
))
271 (slot-value 'intercept
))
273 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
274 "Message args: (&optional new-w)
276 With no argument returns the weight sequence as supplied to m; NIL
277 means an unweighted model. NEW-W sets the weights sequence to NEW-W
278 and recomputes the estimates."
280 (setf (slot-value 'weights
) new-w
)
281 (send self
:needs-computing t
))
282 (slot-value 'weights
))
284 (defmeth regression-model-proto
:total-sum-of-squares
()
287 Returns the total sum of squares around the mean."
288 (if (send self
:needs-computing
) (send self
:compute
))
289 (slot-value 'total-sum-of-squares
))
291 (defmeth regression-model-proto
:residual-sum-of-squares
()
294 Returns the residual sum of squares for the model."
295 (if (send self
:needs-computing
) (send self
:compute
))
296 (slot-value 'residual-sum-of-squares
))
298 (defmeth regression-model-proto
:basis
()
301 Returns the indices of the variables used in fitting the model, in a
303 (if (send self
:needs-computing
)
304 (send self
:compute
))
305 (if (typep (slot-value 'basis
) 'sequence
)
307 (list (slot-value 'basis
))))
310 (defmeth regression-model-proto
:sweep-matrix
()
313 Returns the swept sweep matrix. For internal use"
314 (if (send self
:needs-computing
)
315 (send self
:compute
))
316 (slot-value 'sweep-matrix
))
318 (defmeth regression-model-proto
:included
(&optional new-included
)
319 "Message args: (&optional new-included)
321 With no argument, NIL means a case is not used in calculating
322 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
323 of length of y of nil and t to select cases. Estimates are
325 (when (and new-included
326 (= (length new-included
) (send self
:num-cases
)))
327 (setf (slot-value 'included
) (copy-seq new-included
))
328 (send self
:needs-computing t
))
329 (if (slot-value 'included
)
330 (slot-value 'included
)
331 (repeat t
(send self
:num-cases
))))
333 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
334 "Message args: (&optional (names nil set))
336 With no argument returns the predictor names. NAMES sets the names."
337 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
338 (let ((p (array-dimension (send self
:x
) 1))
339 (p-names (slot-value 'predictor-names
)))
340 (if (not (and p-names
(= (length p-names
) p
)))
341 (setf (slot-value 'predictor-names
)
342 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
344 (slot-value 'predictor-names
))
346 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
347 "Message args: (&optional name)
349 With no argument returns the response name. NAME sets the name."
351 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
352 (slot-value 'response-name
))
354 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
355 "Message args: (&optional labels)
356 With no argument returns the case-labels. LABELS sets the labels."
357 (if set
(setf (slot-value 'case-labels
)
359 (mapcar #'string labels
)
360 (mapcar #'(lambda (x) (format nil
"~d" x
))
361 (iseq 0 (- (send self
:num-cases
) 1))))))
362 (slot-value 'case-labels
))
366 ;;; None of these methods access any slots directly.
369 (defmeth regression-model-proto
:num-cases
()
371 Returns the number of cases in the model."
372 (length (send self
:y
)))
374 (defmeth regression-model-proto
:num-included
()
376 Returns the number of cases used in the computations."
377 (sum (if-else (send self
:included
) 1 0)))
379 (defmeth regression-model-proto
:num-coefs
()
381 Returns the number of coefficients in the fit model (including the
382 intercept if the model includes one)."
383 (if (send self
:intercept
)
384 (+ 1 (length (send self
:basis
)))
385 (length (send self
:basis
))))
387 (defmeth regression-model-proto
:df
()
389 Returns the number of degrees of freedom in the model."
390 (- (send self
:num-included
) (send self
:num-coefs
)))
392 (defmeth regression-model-proto
:x-matrix
()
394 Returns the X matrix for the model, including a column of 1's, if
395 appropriate. Columns of X matrix correspond to entries in basis."
396 (let ((m (select (send self
:x
)
397 (iseq 0 (- (send self
:num-cases
) 1))
398 (send self
:basis
))))
399 (if (send self
:intercept
)
400 (bind-columns (repeat 1 (send self
:num-cases
)) m
)
403 (defmeth regression-model-proto
:leverages
()
405 Returns the diagonal elements of the hat matrix."
406 (let* ((weights (send self
:weights
))
407 (x (send self
:x-matrix
))
409 (matmult (* (matmult x
(send self
:xtxinv
)) x
)
410 (repeat 1 (send self
:num-coefs
)))))
411 (if weights
(* weights raw-levs
) raw-levs
)))
413 (defmeth regression-model-proto
:fit-values
()
415 Returns the fitted values for the model."
416 (matmult (send self
:x-matrix
) (send self
:coef-estimates
)))
418 (defmeth regression-model-proto
:raw-residuals
()
420 Returns the raw residuals for a model."
421 (- (send self
:y
) (send self
:fit-values
)))
423 (defmeth regression-model-proto
:residuals
()
425 Returns the raw residuals for a model without weights. If the model
426 includes weights the raw residuals times the square roots of the weights
428 (let ((raw-residuals (send self
:raw-residuals
))
429 (weights (send self
:weights
)))
430 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
432 (defmeth regression-model-proto
:sum-of-squares
()
434 Returns the error sum of squares for the model."
435 (send self
:residual-sum-of-squares
))
437 (defmeth regression-model-proto
:sigma-hat
()
439 Returns the estimated standard deviation of the deviations about the
441 (let ((ss (send self
:sum-of-squares
))
442 (df (send self
:df
)))
443 (if (/= df
0) (sqrt (/ ss df
)))))
445 ;; for models without an intercept the 'usual' formula for R^2 can give
446 ;; negative results; hence the max.
447 (defmeth regression-model-proto
:r-squared
()
449 Returns the sample squared multiple correlation coefficient, R squared, for
451 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
454 (defmeth regression-model-proto
:coef-estimates
()
457 Returns the OLS (ordinary least squares) estimates of the regression
458 coefficients. Entries beyond the intercept correspond to entries in
460 (let ((n (array-dimension (send self
:x
) 1))
461 (indices (flatten-list
462 (if (send self
:intercept
)
463 (list 0 (+ 1 (send self
:basis
))) ;; was cons -- why?
464 (list (+ 1 (send self
:basis
))))))
465 (m (send self
:sweep-matrix
)))
466 (format t
"~%REMOVEME2: Coef-ests: ~A ~% ~A ~% ~A ~% ~A"
467 m n indices
(send self
:basis
))
468 (coerce (compound-data-seq (select m
(+ 1 n
) indices
)) 'list
)))
470 (defmeth regression-model-proto
:xtxinv
()
472 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
473 (let ((indices (if (send self
:intercept
)
474 (cons 0 (1+ (send self
:basis
)))
475 (1+ (send self
:basis
)))))
476 (select (send self
:sweep-matrix
) indices indices
)))
478 (defmeth regression-model-proto
:coef-standard-errors
()
480 Returns estimated standard errors of coefficients. Entries beyond the
481 intercept correspond to entries in basis."
482 (let ((s (send self
:sigma-hat
)))
483 (if s
(* (send self
:sigma-hat
) (sqrt (diagonal (send self
:xtxinv
)))))))
485 (defmeth regression-model-proto
:studentized-residuals
()
487 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
488 (let ((res (send self
:residuals
))
489 (lev (send self
:leverages
))
490 (sig (send self
:sigma-hat
))
491 (inc (send self
:included
)))
493 (/ res
(* sig
(sqrt (pmax .00001 (- 1 lev
)))))
494 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
496 (defmeth regression-model-proto
:externally-studentized-residuals
()
498 Computes the externally studentized residuals."
499 (let* ((res (send self
:studentized-residuals
))
500 (df (send self
:df
)))
501 (if-else (send self
:included
)
502 (* res
(sqrt (/ (- df
1) (- df
(^ res
2)))))
505 (defmeth regression-model-proto
:cooks-distances
()
507 Computes Cook's distances."
508 (let ((lev (send self
:leverages
))
509 (res (/ (^
(send self
:studentized-residuals
) 2)
510 (send self
:num-coefs
))))
511 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
514 (defun plot-points (x y
&rest args
)
516 (declare (ignore x y args
))
517 (error "Graphics not implemented yet."))
519 ;; Can not plot points yet!!
520 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
521 "Message args: (&optional x-values)
522 Opens a window with a plot of the residuals. If X-VALUES are not supplied
523 the fitted values are used. The plot can be linked to other plots with the
524 link-views function. Returns a plot object."
525 (plot-points (if x-values x-values
(send self
:fit-values
))
526 (send self
:residuals
)
527 :title
"Residual Plot"
528 :point-labels
(send self
:case-labels
)))
530 (defmeth regression-model-proto
:plot-bayes-residuals
532 "Message args: (&optional x-values)
534 Opens a window with a plot of the standardized residuals and two
535 standard error bars for the posterior distribution of the actual
536 deviations from the line. See Chaloner and Brant. If X-VALUES are not
537 supplied the fitted values are used. The plot can be linked to other
538 plots with the link-views function. Returns a plot object."
540 (let* ((r (/ (send self
:residuals
)
541 (send self
:sigma-hat
)))
542 (d (* 2 (sqrt (send self
:leverages
))))
545 (x-values (if x-values x-values
(send self
:fit-values
)))
546 (p (plot-points x-values r
547 :title
"Bayes Residual Plot"
548 :point-labels
(send self
:case-labels
))))
549 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
550 x-values low x-values high
)
551 (send p
:adjust-to-data
)