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
48 (defvar regression-model-proto nil
49 "Prototype for all regression model instances.")
50 (defproto regression-model-proto
51 '(x y intercept sweep-matrix basis weights
54 residual-sum-of-squares
61 "Normal Linear Regression Model")
63 (defun regression-model (x y
&key
67 (included (repeat t
(length y
)))
71 (doc "Undocumented Regression Model Instance")
73 "Args: (x y &key (intercept T) (print T) (weights nil)
74 included predictor-names response-name case-labels)
75 X - list of independent variables or X matrix
76 Y - dependent variable.
77 INTERCEPT - T to include (default), NIL for no intercept
78 PRINT - if not NIL print summary information
79 WEIGHTS - if supplied should be the same length as Y; error
81 assumed to be inversely proportional to WEIGHTS
82 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
83 - sequences of strings or symbols.
84 INCLUDED - if supplied should be the same length as Y, with
85 elements nil to skip a in computing estimates (but not
86 in residual analysis).
87 Returns a regression model object. To examine the model further assign the
88 result to a variable and send it messages.
89 Example (data are in file absorbtion.lsp in the sample data directory):
90 (def m (regression-model (list iron aluminum) absorbtion))
91 (send m :help) (send m :plot-residuals)"
94 ((typep x
'vector
) (list x
))
96 (numberp (car x
))) (list x
))
98 (m (send regression-model-proto
:new
)))
101 (send m
:x
(if (matrixp x
) x
(apply #'bind-columns x
)))
103 (send m
:intercept intercept
)
104 (send m
:weights weights
)
105 (send m
:included included
)
106 (send m
:predictor-names predictor-names
)
107 (send m
:response-name response-name
)
108 (send m
:case-labels case-labels
)
112 (format t
"~S~%" (send m
:doc
))
113 (format t
"X: ~S~%" (send m
:x
))
114 (format t
"Y: ~S~%" (send m
:y
))))
115 (if print
(send m
:display
))
118 (defmeth regression-model-proto
:isnew
()
119 (send self
:needs-computing t
))
121 (defmeth regression-model-proto
:save
()
123 Returns an expression that will reconstruct the regression model."
124 `(regression-model ',(send self
:x
)
126 :intercept
',(send self
:intercept
)
127 :weights
',(send self
:weights
)
128 :included
',(send self
:included
)
129 :predictor-names
',(send self
:predictor-names
)
130 :response-name
',(send self
:response-name
)
131 :case-labels
',(send self
:case-labels
)))
133 ;;; Computing and Display Methods
135 (defmeth regression-model-proto
:compute
()
137 Recomputes the estimates. For internal use by other messages"
138 (let* ((included (if-else (send self
:included
) 1 0))
141 (intercept (send self
:intercept
))
142 (weights (send self
:weights
))
143 (w (if weights
(* included weights
) included
))
144 (m (make-sweep-matrix x y w
)) ;;; ERROR HERE
145 (n (array-dimension x
1))
146 (p (- (array-dimension m
0) 1))
148 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation
(column-list x
)))))
149 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
152 (sweep-operator m
(iseq 1 n
) tol
)
153 (sweep-operator m
(iseq 0 n
) (cons 0.0 tol
)))))
155 "~%REMOVEME: regr-mdl-prto :compute =~A~%~A~%~A~%~A~%~A~%"
157 (setf (slot-value 'sweep-matrix
) (first sweep-result
))
158 (setf (slot-value 'total-sum-of-squares
) tss
)
159 (setf (slot-value 'residual-sum-of-squares
)
160 (aref (first sweep-result
) p p
))
161 (setf (slot-value 'basis
)
162 (let ((b (remove 0 (second sweep-result
))))
163 (if b
(- (reduce #'-
(reverse b
)) 1)
164 (error "no columns could be swept"))))))
166 (defmeth regression-model-proto
:needs-computing
(&optional set
)
167 ;;(declare (ignore self))
168 (if set
(setf (slot-value 'sweep-matrix
) nil
))
169 (null (slot-value 'sweep-matrix
)))
171 (defmeth regression-model-proto
:display
()
173 Prints the least squares regression summary. Variables not used in the fit
174 are marked as aliased."
175 (let ((coefs (coerce (send self
:coef-estimates
) 'list
))
176 (se-s (send self
:coef-standard-errors
))
178 (p-names (send self
:predictor-names
)))
179 (if (send self
:weights
)
180 (format t
"~%Weighted Least Squares Estimates:~2%")
181 (format t
"~%Least Squares Estimates:~2%"))
182 (when (send self
:intercept
)
183 (format t
"Constant ~10f ~A~%"
184 (car coefs
) (list (car se-s
)))
185 (setf coefs
(cdr coefs
))
186 (setf se-s
(cdr se-s
)))
187 (dotimes (i (array-dimension x
1))
189 ((member i
(send self
:basis
))
190 (format t
"~22a ~10f ~A~%"
191 (select p-names i
) (car coefs
) (list (car se-s
)))
192 (setf coefs
(cdr coefs
) se-s
(cdr se-s
)))
193 (t (format t
"~22a aliased~%" (select p-names i
)))))
195 (format t
"R Squared: ~10f~%" (send self
:r-squared
))
196 (format t
"Sigma hat: ~10f~%" (send self
:sigma-hat
))
197 (format t
"Number of cases: ~10d~%" (send self
:num-cases
))
198 (if (/= (send self
:num-cases
) (send self
:num-included
))
199 (format t
"Number of cases used: ~10d~%" (send self
:num-included
)))
200 (format t
"Degrees of freedom: ~10d~%" (send self
:df
))
203 ;;; Slot accessors and mutators
205 (defmeth regression-model-proto
:doc
(&optional new-doc
)
206 "Message args: (&optional new-doc)
208 With no argument returns the DOC-STRING as supplied to m. With an argument
209 NEW-DOC sets the DOC-STRING to NEW-DOC."
210 (when (and new-doc
(stringp new-doc
))
211 (setf (slot-value 'doc
) new-doc
))
215 (defmeth regression-model-proto
:x
(&optional new-x
)
216 "Message args: (&optional new-x)
218 With no argument returns the x matrix as supplied to m. With an
219 argument, NEW-X sets the x matrix to NEW-X and recomputes the
222 (when (and new-x
(matrixp new-x
))
223 (setf (slot-value 'x
) new-x
)
224 (send self
:needs-computing t
))
227 (defmeth regression-model-proto
:y
(&optional new-y
)
228 "Message args: (&optional new-y)
230 With no argument returns the y sequence as supplied to m. With an
231 argument, NEW-Y sets the y sequence to NEW-Y and recomputes the
234 (or (matrixp new-y
) (typep new-y
'sequence
)))
235 (setf (slot-value 'y
) new-y
)
236 (send self
:needs-computing t
))
239 (defmeth regression-model-proto
:intercept
(&optional
(val nil set
))
240 "Message args: (&optional new-intercept)
242 With no argument returns T if the model includes an intercept term,
243 nil if not. With an argument NEW-INTERCEPT the model is changed to
244 include or exclude an intercept, according to the value of
247 (setf (slot-value 'intercept
) val
)
248 (send self
:needs-computing t
))
249 (slot-value 'intercept
))
251 (defmeth regression-model-proto
:weights
(&optional
(new-w nil set
))
252 "Message args: (&optional new-w)
254 With no argument returns the weight sequence as supplied to m; NIL
255 means an unweighted model. NEW-W sets the weights sequence to NEW-W
256 and recomputes the estimates."
258 (setf (slot-value 'weights
) new-w
)
259 (send self
:needs-computing t
))
260 (slot-value 'weights
))
262 (defmeth regression-model-proto
:total-sum-of-squares
()
265 Returns the total sum of squares around the mean."
266 (if (send self
:needs-computing
) (send self
:compute
))
267 (slot-value 'total-sum-of-squares
))
269 (defmeth regression-model-proto
:residual-sum-of-squares
()
272 Returns the residual sum of squares for the model."
273 (if (send self
:needs-computing
) (send self
:compute
))
274 (slot-value 'residual-sum-of-squares
))
276 (defmeth regression-model-proto
:basis
()
279 Returns the indices of the variables used in fitting the model, in a
281 (if (send self
:needs-computing
)
282 (send self
:compute
))
283 (if (typep (slot-value 'basis
) 'sequence
)
285 (list (slot-value 'basis
))))
290 (defmeth regression-model-proto
:sweep-matrix
()
293 Returns the swept sweep matrix. For internal use"
294 (if (send self
:needs-computing
) (send self
:compute
))
295 (slot-value 'sweep-matrix
))
297 (defmeth regression-model-proto
:included
(&optional new-included
)
298 "Message args: (&optional new-included)
300 With no argument, NIL means a case is not used in calculating
301 estimates, and non-nil means it is used. NEW-INCLUDED is a sequence
302 of length of y of nil and t to select cases. Estimates are
304 (when (and new-included
305 (= (length new-included
) (send self
:num-cases
)))
306 (setf (slot-value 'included
) (copy-seq new-included
))
307 (send self
:needs-computing t
))
308 (if (slot-value 'included
)
309 (slot-value 'included
)
310 (repeat t
(send self
:num-cases
))))
312 (defmeth regression-model-proto
:predictor-names
(&optional
(names nil set
))
313 "Message args: (&optional (names nil set))
315 With no argument returns the predictor names. NAMES sets the names."
316 (if set
(setf (slot-value 'predictor-names
) (mapcar #'string names
)))
317 (let ((p (array-dimension (send self
:x
) 1))
318 (p-names (slot-value 'predictor-names
)))
319 (if (not (and p-names
(= (length p-names
) p
)))
320 (setf (slot-value 'predictor-names
)
321 (mapcar #'(lambda (a) (format nil
"Variable ~a" a
))
323 (slot-value 'predictor-names
))
325 (defmeth regression-model-proto
:response-name
(&optional
(name "Y" set
))
326 "Message args: (&optional name)
328 With no argument returns the response name. NAME sets the name."
329 ;;(declare (ignore self))
330 (if set
(setf (slot-value 'response-name
) (if name
(string name
) "Y")))
331 (slot-value 'response-name
))
333 (defmeth regression-model-proto
:case-labels
(&optional
(labels nil set
))
334 "Message args: (&optional labels)
335 With no argument returns the case-labels. LABELS sets the labels."
336 (if set
(setf (slot-value 'case-labels
)
338 (mapcar #'string labels
)
339 (mapcar #'(lambda (x) (format nil
"~d" x
))
340 (iseq 0 (- (send self
:num-cases
) 1))))))
341 (slot-value 'case-labels
))
345 ;;; None of these methods access any slots directly.
348 (defmeth regression-model-proto
:num-cases
()
350 Returns the number of cases in the model."
351 (length (send self
:y
)))
353 (defmeth regression-model-proto
:num-included
()
355 Returns the number of cases used in the computations."
356 (sum (if-else (send self
:included
) 1 0)))
358 (defmeth regression-model-proto
:num-coefs
()
360 Returns the number of coefficients in the fit model (including the
361 intercept if the model includes one)."
362 (if (send self
:intercept
)
363 (+ 1 (length (send self
:basis
)))
364 (length (send self
:basis
))))
366 (defmeth regression-model-proto
:df
()
368 Returns the number of degrees of freedom in the model."
369 (- (send self
:num-included
) (send self
:num-coefs
)))
371 (defmeth regression-model-proto
:x-matrix
()
373 Returns the X matrix for the model, including a column of 1's, if
374 appropriate. Columns of X matrix correspond to entries in basis."
375 (let ((m (select (send self
:x
)
376 (iseq 0 (- (send self
:num-cases
) 1))
377 (send self
:basis
))))
378 (if (send self
:intercept
)
379 (bind-columns (repeat 1 (send self
:num-cases
)) m
)
382 (defmeth regression-model-proto
:leverages
()
384 Returns the diagonal elements of the hat matrix."
385 (let* ((weights (send self
:weights
))
386 (x (send self
:x-matrix
))
388 (matmult (* (matmult x
(send self
:xtxinv
)) x
)
389 (repeat 1 (send self
:num-coefs
)))))
390 (if weights
(* weights raw-levs
) raw-levs
)))
392 (defmeth regression-model-proto
:fit-values
()
394 Returns the fitted values for the model."
395 (matmult (send self
:x-matrix
) (send self
:coef-estimates
)))
397 (defmeth regression-model-proto
:raw-residuals
()
399 Returns the raw residuals for a model."
400 (- (send self
:y
) (send self
:fit-values
)))
402 (defmeth regression-model-proto
:residuals
()
404 Returns the raw residuals for a model without weights. If the model
405 includes weights the raw residuals times the square roots of the weights
407 (let ((raw-residuals (send self
:raw-residuals
))
408 (weights (send self
:weights
)))
409 (if weights
(* (sqrt weights
) raw-residuals
) raw-residuals
)))
411 (defmeth regression-model-proto
:sum-of-squares
()
413 Returns the error sum of squares for the model."
414 (send self
:residual-sum-of-squares
))
416 (defmeth regression-model-proto
:sigma-hat
()
418 Returns the estimated standard deviation of the deviations about the
420 (let ((ss (send self
:sum-of-squares
))
421 (df (send self
:df
)))
422 (if (/= df
0) (sqrt (/ ss df
)))))
424 ;; for models without an intercept the 'usual' formula for R^2 can give
425 ;; negative results; hence the max.
426 (defmeth regression-model-proto
:r-squared
()
428 Returns the sample squared multiple correlation coefficient, R squared, for
430 (max (- 1 (/ (send self
:sum-of-squares
) (send self
:total-sum-of-squares
)))
433 (defmeth regression-model-proto
:coef-estimates
()
436 Returns the OLS (ordinary least squares) estimates of the regression
437 coefficients. Entries beyond the intercept correspond to entries in
439 (let ((n (array-dimension (send self
:x
) 1))
440 (indices (flatten-list
441 (if (send self
:intercept
)
442 (list 0 (+ 1 (send self
:basis
))) ;; was cons -- why?
443 (list (+ 1 (send self
:basis
))))))
444 (m (send self
:sweep-matrix
)))
445 (format t
"~%REMOVEME2: Coef-ests: ~A ~% ~A ~% ~A ~% ~A"
446 m n indices
(send self
:basis
))
447 (coerce (compound-data-seq (select m
(+ 1 n
) indices
)) 'list
)))
449 (defmeth regression-model-proto
:xtxinv
()
451 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
452 (let ((indices (if (send self
:intercept
)
453 (cons 0 (1+ (send self
:basis
)))
454 (1+ (send self
:basis
)))))
455 (select (send self
:sweep-matrix
) indices indices
)))
457 (defmeth regression-model-proto
:coef-standard-errors
()
459 Returns estimated standard errors of coefficients. Entries beyond the
460 intercept correspond to entries in basis."
461 (let ((s (send self
:sigma-hat
)))
462 (if s
(* (send self
:sigma-hat
) (sqrt (diagonal (send self
:xtxinv
)))))))
464 (defmeth regression-model-proto
:studentized-residuals
()
466 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
467 (let ((res (send self
:residuals
))
468 (lev (send self
:leverages
))
469 (sig (send self
:sigma-hat
))
470 (inc (send self
:included
)))
472 (/ res
(* sig
(sqrt (pmax .00001 (- 1 lev
)))))
473 (/ res
(* sig
(sqrt (+ 1 lev
)))))))
475 (defmeth regression-model-proto
:externally-studentized-residuals
()
477 Computes the externally studentized residuals."
478 (let* ((res (send self
:studentized-residuals
))
479 (df (send self
:df
)))
480 (if-else (send self
:included
)
481 (* res
(sqrt (/ (- df
1) (- df
(^ res
2)))))
484 (defmeth regression-model-proto
:cooks-distances
()
486 Computes Cook's distances."
487 (let ((lev (send self
:leverages
))
488 (res (/ (^
(send self
:studentized-residuals
) 2)
489 (send self
:num-coefs
))))
490 (if-else (send self
:included
) (* res
(/ lev
(- 1 lev
) )) (* res lev
))))
493 (defun plot-points (x y
&rest args
)
495 (declare (ignore x y args
))
496 (error "Graphics not implemented yet."))
498 ;; Can not plot points yet!!
499 (defmeth regression-model-proto
:plot-residuals
(&optional x-values
)
500 "Message args: (&optional x-values)
501 Opens a window with a plot of the residuals. If X-VALUES are not supplied
502 the fitted values are used. The plot can be linked to other plots with the
503 link-views function. Returns a plot object."
504 (plot-points (if x-values x-values
(send self
:fit-values
))
505 (send self
:residuals
)
506 :title
"Residual Plot"
507 :point-labels
(send self
:case-labels
)))
509 (defmeth regression-model-proto
:plot-bayes-residuals
511 "Message args: (&optional x-values)
513 Opens a window with a plot of the standardized residuals and two
514 standard error bars for the posterior distribution of the actual
515 deviations from the line. See Chaloner and Brant. If X-VALUES are not
516 supplied the fitted values are used. The plot can be linked to other
517 plots with the link-views function. Returns a plot object."
519 (let* ((r (/ (send self
:residuals
)
520 (send self
:sigma-hat
)))
521 (d (* 2 (sqrt (send self
:leverages
))))
524 (x-values (if x-values x-values
(send self
:fit-values
)))
525 (p (plot-points x-values r
526 :title
"Bayes Residual Plot"
527 :point-labels
(send self
:case-labels
))))
528 (map 'list
#'(lambda (a b c d
) (send p
:plotline a b c d nil
))
529 x-values low x-values high
)
530 (send p
:adjust-to-data
)