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 (let ((mat-y (coerce-seq-to-1d-col-matrix new-y
)))
260 (setf (slot-value 'y
) new-y
)
261 (send self
:needs-computing t
)))
264 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
265 "Message args: (&optional new-intercept)
267 With no argument returns T if the model includes an intercept term,
268 nil if not. With an argument NEW-INTERCEPT the model is changed to
269 include or exclude an intercept, according to the value of
272 (setf (slot-value 'intercept
) val
)
273 (send self
:needs-computing t
))
274 (slot-value 'intercept
))
276 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
277 "Message args: (&optional new-w)
279 With no argument returns the weight sequence as supplied to m; NIL
280 means an unweighted model. NEW-W sets the weights sequence to NEW-W
281 and recomputes the estimates."
283 (setf (slot-value 'weights
) new-w
)
284 (send self
:needs-computing t
))
285 (slot-value 'weights
))
287 (defmeth regression-model-proto
:total-sum-of-squares
()
290 Returns the total sum of squares around the mean."
291 (if (send self
:needs-computing
) (send self
:compute
))
292 (slot-value 'total-sum-of-squares
))
294 (defmeth regression-model-proto
:residual-sum-of-squares
()
297 Returns the residual sum of squares for the model."
298 (if (send self
:needs-computing
) (send self
:compute
))
299 (slot-value 'residual-sum-of-squares
))
301 (defmeth regression-model-proto
:basis
()
304 Returns the indices of the variables used in fitting the model, in a
306 (if (send self
:needs-computing
)
307 (send self
:compute
))
308 (if (typep (slot-value 'basis
) 'sequence
)
310 (list (slot-value 'basis
))))
313 (defmeth regression-model-proto
:sweep-matrix
()
316 Returns the swept sweep matrix. For internal use"
317 (if (send self
:needs-computing
)
318 (send self
:compute
))
319 (slot-value 'sweep-matrix
))
321 (defmeth regression-model-proto
:included
(&optional new-included
)
322 "Message args: (&optional new-included)
324 With no argument, NIL means a case is not used in calculating
325 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
326 of length of y of nil and t to select cases. Estimates are
328 (when (and new-included
329 (= (length new-included
) (send self
:num-cases
)))
330 (setf (slot-value 'included
) (copy-seq new-included
))
331 (send self
:needs-computing t
))
332 (if (slot-value 'included
)
333 (slot-value 'included
)
334 (repeat t
(send self
:num-cases
))))
336 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
337 "Message args: (&optional (names nil set))
339 With no argument returns the predictor names. NAMES sets the names."
340 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
341 (let ((p (array-dimension (send self
:x
) 1))
342 (p-names (slot-value 'predictor-names
)))
343 (if (not (and p-names
(= (length p-names
) p
)))
344 (setf (slot-value 'predictor-names
)
345 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
347 (slot-value 'predictor-names
))
349 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
350 "Message args: (&optional name)
352 With no argument returns the response name. NAME sets the name."
354 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
355 (slot-value 'response-name
))
357 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
358 "Message args: (&optional labels)
359 With no argument returns the case-labels. LABELS sets the labels."
360 (if set
(setf (slot-value 'case-labels
)
362 (mapcar #'string labels
)
363 (mapcar #'(lambda (x) (format nil
"~d" x
))
364 (iseq 0 (- (send self
:num-cases
) 1))))))
365 (slot-value 'case-labels
))
369 ;;; None of these methods access any slots directly.
372 (defmeth regression-model-proto
:num-cases
()
374 Returns the number of cases in the model."
375 (length (send self
:y
)))
377 (defmeth regression-model-proto
:num-included
()
379 Returns the number of cases used in the computations."
380 (sum (if-else (send self
:included
) 1 0)))
382 (defmeth regression-model-proto
:num-coefs
()
384 Returns the number of coefficients in the fit model (including the
385 intercept if the model includes one)."
386 (if (send self
:intercept
)
387 (+ 1 (length (send self
:basis
)))
388 (length (send self
:basis
))))
390 (defmeth regression-model-proto
:df
()
392 Returns the number of degrees of freedom in the model."
393 (- (send self
:num-included
) (send self
:num-coefs
)))
395 (defmeth regression-model-proto
:x-matrix
()
397 Returns the X matrix for the model, including a column of 1's, if
398 appropriate. Columns of X matrix correspond to entries in basis."
399 (let ((m (select (send self
:x
)
400 (iseq 0 (- (send self
:num-cases
) 1))
401 (send self
:basis
))))
402 (if (send self
:intercept
)
403 (bind-columns (repeat 1 (send self
:num-cases
)) m
)
406 (defmeth regression-model-proto
:leverages
()
408 Returns the diagonal elements of the hat matrix."
409 (let* ((weights (send self
:weights
))
410 (x (send self
:x-matrix
))
412 (matmult (* (matmult x
(send self
:xtxinv
)) x
)
413 (repeat 1 (send self
:num-coefs
)))))
414 (if weights
(* weights raw-levs
) raw-levs
)))
416 (defmeth regression-model-proto
:fit-values
()
418 Returns the fitted values for the model."
419 (matmult (send self
:x-matrix
) (send self
:coef-estimates
)))
421 (defmeth regression-model-proto
:raw-residuals
()
423 Returns the raw residuals for a model."
424 (- (send self
:y
) (send self
:fit-values
)))
426 (defmeth regression-model-proto
:residuals
()
428 Returns the raw residuals for a model without weights. If the model
429 includes weights the raw residuals times the square roots of the weights
431 (let ((raw-residuals (send self
:raw-residuals
))
432 (weights (send self
:weights
)))
433 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
435 (defmeth regression-model-proto
:sum-of-squares
()
437 Returns the error sum of squares for the model."
438 (send self
:residual-sum-of-squares
))
440 (defmeth regression-model-proto
:sigma-hat
()
442 Returns the estimated standard deviation of the deviations about the
444 (let ((ss (send self
:sum-of-squares
))
445 (df (send self
:df
)))
446 (if (/= df
0) (sqrt (/ ss df
)))))
448 ;; for models without an intercept the 'usual' formula for R^2 can give
449 ;; negative results; hence the max.
450 (defmeth regression-model-proto
:r-squared
()
452 Returns the sample squared multiple correlation coefficient, R squared, for
454 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
457 (defmeth regression-model-proto
:coef-estimates
()
460 Returns the OLS (ordinary least squares) estimates of the regression
461 coefficients. Entries beyond the intercept correspond to entries in
463 (let ((n (array-dimension (send self
:x
) 1))
464 (indices (flatten-list
465 (if (send self
:intercept
)
466 (list 0 (+ 1 (send self
:basis
))) ;; was cons -- why?
467 (list (+ 1 (send self
:basis
))))))
468 (m (send self
:sweep-matrix
)))
469 (format t
"~%REMOVEME2: Coef-ests: ~A ~% ~A ~% ~A ~% ~A"
470 m n indices
(send self
:basis
))
471 (coerce (compound-data-seq (select m
(+ 1 n
) indices
)) 'list
)))
473 (defmeth regression-model-proto
:xtxinv
()
475 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
476 (let ((indices (if (send self
:intercept
)
477 (cons 0 (1+ (send self
:basis
)))
478 (1+ (send self
:basis
)))))
479 (select (send self
:sweep-matrix
) indices indices
)))
481 (defmeth regression-model-proto
:coef-standard-errors
()
483 Returns estimated standard errors of coefficients. Entries beyond the
484 intercept correspond to entries in basis."
485 (let ((s (send self
:sigma-hat
)))
486 (if s
(* (send self
:sigma-hat
) (sqrt (diagonal (send self
:xtxinv
)))))))
488 (defmeth regression-model-proto
:studentized-residuals
()
490 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
491 (let ((res (send self
:residuals
))
492 (lev (send self
:leverages
))
493 (sig (send self
:sigma-hat
))
494 (inc (send self
:included
)))
496 (/ res
(* sig
(sqrt (pmax .00001 (- 1 lev
)))))
497 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
499 (defmeth regression-model-proto
:externally-studentized-residuals
()
501 Computes the externally studentized residuals."
502 (let* ((res (send self
:studentized-residuals
))
503 (df (send self
:df
)))
504 (if-else (send self
:included
)
505 (* res
(sqrt (/ (- df
1) (- df
(^ res
2)))))
508 (defmeth regression-model-proto
:cooks-distances
()
510 Computes Cook's distances."
511 (let ((lev (send self
:leverages
))
512 (res (/ (^
(send self
:studentized-residuals
) 2)
513 (send self
:num-coefs
))))
514 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
517 (defun plot-points (x y
&rest args
)
519 (declare (ignore x y args
))
520 (error "Graphics not implemented yet."))
522 ;; Can not plot points yet!!
523 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
524 "Message args: (&optional x-values)
525 Opens a window with a plot of the residuals. If X-VALUES are not supplied
526 the fitted values are used. The plot can be linked to other plots with the
527 link-views function. Returns a plot object."
528 (plot-points (if x-values x-values
(send self
:fit-values
))
529 (send self
:residuals
)
530 :title
"Residual Plot"
531 :point-labels
(send self
:case-labels
)))
533 (defmeth regression-model-proto
:plot-bayes-residuals
535 "Message args: (&optional x-values)
537 Opens a window with a plot of the standardized residuals and two
538 standard error bars for the posterior distribution of the actual
539 deviations from the line. See Chaloner and Brant. If X-VALUES are not
540 supplied the fitted values are used. The plot can be linked to other
541 plots with the link-views function. Returns a plot object."
543 (let* ((r (/ (send self
:residuals
)
544 (send self
:sigma-hat
)))
545 (d (* 2 (sqrt (send self
:leverages
))))
548 (x-values (if x-values x-values
(send self
:fit-values
)))
549 (p (plot-points x-values r
550 :title
"Bayes Residual Plot"
551 :point-labels
(send self
:case-labels
))))
552 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
553 x-values low x-values high
)
554 (send p
:adjust-to-data
)