We use CFFI, so don't bother spec'ing. Additional suggestions for new API.
[CommonLispStat.git] / regression.lsp
blob0160fea18ff68df89ef6f5ae38c1715f47e60afa
1 ;;; -*- mode: lisp -*-
2 ;;;
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
6 ;;; Common Lisp.
8 ;;;;
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 ;;;;
16 ;;;; Incorporates modifications suggested by Sandy Weisberg.
17 ;;;;
19 (in-package :cl-user)
21 (defpackage :lisp-stat-regression-linear
22 (:use :common-lisp
23 :lisp-stat-object-system
24 :lisp-stat-basics
25 :lisp-stat-compound-data
26 :lisp-stat-math
27 :lisp-stat-matrix
28 :lisp-stat-linalg
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 conjugate realpart imagpart phase
37 min max logand logior logxor lognot ffloor fceiling
38 ftruncate fround signum cis)
39 (:export regression-model regression-model-proto x y intercept sweep-matrix
40 basis weights included total-sum-of-squares residual-sum-of-squares
41 predictor-names response-name case-labels))
43 (in-package :lisp-stat-regression-linear)
45 ;;; Regresion Model Prototype
47 (defproto regression-model-proto
48 '(x y intercept sweep-matrix basis weights
49 included
50 total-sum-of-squares
51 residual-sum-of-squares
52 predictor-names
53 response-name
54 case-labels)
56 *object*
57 "Normal Linear Regression Model")
59 (defun regression-model (x y &key
60 (intercept T)
61 (print T)
62 weights
63 (included (repeat t (length y)))
64 predictor-names
65 response-name
66 case-labels)
67 "Args: (x y &key (intercept T) (print T) weights
68 included predictor-names response-name case-labels)
69 X - list of independent variables or X matrix
70 Y - dependent variable.
71 INTERCEPT - T to include (default), NIL for no intercept
72 PRINT - if not NIL print summary information
73 WEIGHTS - if supplied should be the same length as Y; error variances are
74 assumed to be inversely proportional to WEIGHTS
75 PREDICTOR-NAMES, RESPONSE-NAME, CASE-LABELS
76 - sequences of strings or symbols.
77 INCLUDED - if supplied should be the same length as Y, with elements nil
78 to skip a in computing estimates (but not in residual analysis).
79 Returns a regression model object. To examine the model further assign the
80 result to a variable and send it messages.
81 Example (data are in file absorbtion.lsp in the sample data directory/folder):
82 (def m (regression-model (list iron aluminum) absorbtion))
83 (send m :help) (send m :plot-residuals)"
84 (let ((x (cond
85 ((matrixp x) x)
86 ((vectorp x) (list x))
87 ((and (consp x) (numberp (car x))) (list x))
88 (t x)))
89 (m (send regression-model-proto :new)))
90 (send m :x (if (matrixp x) x (apply #'bind-columns x)))
91 (send m :y y)
92 (send m :intercept intercept)
93 (send m :weights weights)
94 (send m :included included)
95 (send m :predictor-names predictor-names)
96 (send m :response-name response-name)
97 (send m :case-labels case-labels)
98 (if print (send m :display))
99 m))
101 (defmeth regression-model-proto :isnew ()
102 (send self :needs-computing t))
104 (defmeth regression-model-proto :save ()
105 "Message args: ()
106 Returns an expression that will reconstruct the regression model."
107 `(regression-model ',(send self :x)
108 ',(send self :y)
109 :intercept ',(send self :intercept)
110 :weights ',(send self :weights)
111 :included ',(send self :included)
112 :predictor-names ',(send self :predictor-names)
113 :response-name ',(send self :response-name)
114 :case-labels ',(send self :case-labels)))
116 ;;; Computing and Display Methods
118 (defmeth regression-model-proto :compute ()
119 "Message args: ()
120 Recomputes the estimates. For internal use by other messages"
121 (let* ((included (if-else (send self :included) 1 0))
122 (x (send self :x))
123 (y (send self :y))
124 (intercept (send self :intercept))
125 (weights (send self :weights))
126 (w (if weights (* included weights) included))
127 (m (make-sweep-matrix x y w))
128 (n (array-dimension x 1))
129 (p (- (array-dimension m 0) 1))
130 (tss (aref m p p))
131 (tol (* 0.001 (reduce #'* (mapcar #'standard-deviation (column-list x)))))
132 ;; (tol (* 0.001 (apply #'* (mapcar #'standard-deviation (column-list x)))))
133 (sweep-result
134 (if intercept
135 (sweep-operator m (iseq 1 n) tol)
136 (sweep-operator m (iseq 0 n) (cons 0.0 tol)))))
137 (setf (slot-value 'sweep-matrix) (first sweep-result))
138 (setf (slot-value 'total-sum-of-squares) tss)
139 (setf (slot-value 'residual-sum-of-squares)
140 (aref (first sweep-result) p p))
141 (setf (slot-value 'basis)
142 (let ((b (remove 0 (second sweep-result))))
143 (if b (- (reduce #'- (reverse b)) 1)
144 (error "no columns could be swept"))))))
146 (defmeth regression-model-proto :needs-computing (&optional set)
147 (if set (setf (slot-value 'sweep-matrix) nil))
148 (null (slot-value 'sweep-matrix)))
150 (defmeth regression-model-proto :display ()
151 "Message args: ()
152 Prints the least squares regression summary. Variables not used in the fit
153 are marked as aliased."
154 (let ((coefs (coerce (send self :coef-estimates) 'list))
155 (se-s (send self :coef-standard-errors))
156 (x (send self :x))
157 (p-names (send self :predictor-names)))
158 (if (send self :weights)
159 (format t "~%Weighted Least Squares Estimates:~2%")
160 (format t "~%Least Squares Estimates:~2%"))
161 (when (send self :intercept)
162 (format t "Constant ~10f ~A~%"
163 (car coefs) (list (car se-s)))
164 (setf coefs (cdr coefs))
165 (setf se-s (cdr se-s)))
166 (dotimes (i (array-dimension x 1))
167 (cond
168 ((member i (send self :basis))
169 (format t "~22a ~10f ~A~%"
170 (select p-names i) (car coefs) (list (car se-s)))
171 (setf coefs (cdr coefs) se-s (cdr se-s)))
172 (t (format t "~22a aliased~%" (select p-names i)))))
173 (format t "~%")
174 (format t "R Squared: ~10f~%" (send self :r-squared))
175 (format t "Sigma hat: ~10f~%" (send self :sigma-hat))
176 (format t "Number of cases: ~10d~%" (send self :num-cases))
177 (if (/= (send self :num-cases) (send self :num-included))
178 (format t "Number of cases used: ~10d~%" (send self :num-included)))
179 (format t "Degrees of freedom: ~10d~%" (send self :df))
180 (format t "~%")))
182 ;;; Slot accessors and mutators
184 (defmeth regression-model-proto :x (&optional new-x)
185 "Message args: (&optional new-x)
186 With no argument returns the x matrix as supplied to m. With an argument
187 NEW-X sets the x matrix to NEW-X and recomputes the estimates."
188 (when (and new-x (matrixp new-x))
189 (setf (slot-value 'x) new-x)
190 (send self :needs-computing t))
191 (slot-value 'x))
193 (defmeth regression-model-proto :y (&optional new-y)
194 "Message args: (&optional new-y)
195 With no argument returns the y sequence as supplied to m. With an argument
196 NEW-Y sets the y sequence to NEW-Y and recomputes the estimates."
197 (when (and new-y (or (matrixp new-y) (sequencep new-y)))
198 (setf (slot-value 'y) new-y)
199 (send self :needs-computing t))
200 (slot-value 'y))
202 (defmeth regression-model-proto :intercept (&optional (val nil set))
203 "Message args: (&optional new-intercept)
204 With no argument returns T if the model includes an intercept term, nil if
205 not. With an argument NEW-INTERCEPT the model is changed to include or
206 exclude an intercept, according to the value of NEW-INTERCEPT."
207 (when set
208 (setf (slot-value 'intercept) val)
209 (send self :needs-computing t))
210 (slot-value 'intercept))
212 (defmeth regression-model-proto :weights (&optional (new-w nil set))
213 "Message args: (&optional new-w)
214 With no argument returns the weight sequence as supplied to m; NIL means
215 an unweighted model. NEW-W sets the weights sequence to NEW-W and
216 recomputes the estimates."
217 (when set
218 (setf (slot-value 'weights) new-w)
219 (send self :needs-computing t))
220 (slot-value 'weights))
222 (defmeth regression-model-proto :total-sum-of-squares ()
223 "Message args: ()
224 Returns the total sum of squares around the mean."
225 (if (send self :needs-computing) (send self :compute))
226 (slot-value 'total-sum-of-squares))
228 (defmeth regression-model-proto :residual-sum-of-squares ()
229 "Message args: ()
230 Returns the residual sum of squares for the model."
231 (if (send self :needs-computing) (send self :compute))
232 (slot-value 'residual-sum-of-squares))
234 (defmeth regression-model-proto :basis ()
235 "Message args: ()
236 Returns the indices of the variables used in fitting the model."
237 (if (send self :needs-computing) (send self :compute))
238 (slot-value 'basis))
240 (defmeth regression-model-proto :sweep-matrix ()
241 "Message args: ()
242 Returns the swept sweep matrix. For internal use"
243 (if (send self :needs-computing) (send self :compute))
244 (slot-value 'sweep-matrix))
246 (defmeth regression-model-proto :included (&optional new-included)
247 "Message args: (&optional new-included)
248 With no argument, NIL means a case is not used in calculating estimates, and non-nil means it is used. NEW-INCLUDED is a sequence of length of y of nil and t to select cases. Estimates are recomputed."
249 (when (and new-included
250 (= (length new-included) (send self :num-cases)))
251 (setf (slot-value 'included) (copy-seq new-included))
252 (send self :needs-computing t))
253 (if (slot-value 'included)
254 (slot-value 'included)
255 (repeat t (send self :num-cases))))
257 (defmeth regression-model-proto :predictor-names (&optional (names nil set))
258 "Message args: (&optional (names nil set))
259 With no argument returns the predictor names. NAMES sets the names."
260 (if set (setf (slot-value 'predictor-names) (mapcar #'string names)))
261 (let ((p (array-dimension (send self :x) 1))
262 (p-names (slot-value 'predictor-names)))
263 (if (not (and p-names (= (length p-names) p)))
264 (setf (slot-value 'predictor-names)
265 (mapcar #'(lambda (a) (format nil "Variable ~a" a))
266 (iseq 0 (- p 1))))))
267 (slot-value 'predictor-names))
269 (defmeth regression-model-proto :response-name (&optional (name "Y" set))
270 "Message args: (&optional name)
271 With no argument returns the response name. NAME sets the name."
272 (if set (setf (slot-value 'response-name) (if name (string name) "Y")))
273 (slot-value 'response-name))
275 (defmeth regression-model-proto :case-labels (&optional (labels nil set))
276 "Message args: (&optional labels)
277 With no argument returns the case-labels. LABELS sets the labels."
278 (if set (setf (slot-value 'case-labels)
279 (if labels
280 (mapcar #'string labels)
281 (mapcar #'(lambda (x) (format nil "~d" x))
282 (iseq 0 (- (send self :num-cases) 1))))))
283 (slot-value 'case-labels))
286 ;;; Other Methods
287 ;;; None of these methods access any slots directly.
290 (defmeth regression-model-proto :num-cases ()
291 "Message args: ()
292 Returns the number of cases in the model."
293 (length (send self :y)))
295 (defmeth regression-model-proto :num-included ()
296 "Message args: ()
297 Returns the number of cases used in the computations."
298 (sum (if-else (send self :included) 1 0)))
300 (defmeth regression-model-proto :num-coefs ()
301 "Message args: ()
302 Returns the number of coefficients in the fit model (including the
303 intercept if the model includes one)."
304 (if (send self :intercept)
305 (+ 1 (length (send self :basis)))
306 (length (send self :basis))))
308 (defmeth regression-model-proto :df ()
309 "Message args: ()
310 Returns the number of degrees of freedom in the model."
311 (- (send self :num-included) (send self :num-coefs)))
313 (defmeth regression-model-proto :x-matrix ()
314 "Message args: ()
315 Returns the X matrix for the model, including a column of 1's, if
316 appropriate. Columns of X matrix correspond to entries in basis."
317 (let ((m (select (send self :x)
318 (iseq 0 (- (send self :num-cases) 1))
319 (send self :basis))))
320 (if (send self :intercept)
321 (bind-columns (repeat 1 (send self :num-cases)) m)
322 m)))
324 (defmeth regression-model-proto :leverages ()
325 "Message args: ()
326 Returns the diagonal elements of the hat matrix."
327 (let* ((weights (send self :weights))
328 (x (send self :x-matrix))
329 (raw-levs
330 (matmult (* (matmult x (send self :xtxinv)) x)
331 (repeat 1 (send self :num-coefs)))))
332 (if weights (* weights raw-levs) raw-levs)))
334 (defmeth regression-model-proto :fit-values ()
335 "Message args: ()
336 Returns the fitted values for the model."
337 (matmult (send self :x-matrix) (send self :coef-estimates)))
339 (defmeth regression-model-proto :raw-residuals ()
340 "Message args: ()
341 Returns the raw residuals for a model."
342 (- (send self :y) (send self :fit-values)))
344 (defmeth regression-model-proto :residuals ()
345 "Message args: ()
346 Returns the raw residuals for a model without weights. If the model
347 includes weights the raw residuals times the square roots of the weights
348 are returned."
349 (let ((raw-residuals (send self :raw-residuals))
350 (weights (send self :weights)))
351 (if weights (* (sqrt weights) raw-residuals) raw-residuals)))
353 (defmeth regression-model-proto :sum-of-squares ()
354 "Message args: ()
355 Returns the error sum of squares for the model."
356 (send self :residual-sum-of-squares))
358 (defmeth regression-model-proto :sigma-hat ()
359 "Message args: ()
360 Returns the estimated standard deviation of the deviations about the
361 regression line."
362 (let ((ss (send self :sum-of-squares))
363 (df (send self :df)))
364 (if (/= df 0) (sqrt (/ ss df)))))
366 ;; for models without an intercept the 'usual' formula for R^2 can give
367 ;; negative results; hence the max.
368 (defmeth regression-model-proto :r-squared ()
369 "Message args: ()
370 Returns the sample squared multiple correlation coefficient, R squared, for
371 the regression."
372 (max (- 1 (/ (send self :sum-of-squares) (send self :total-sum-of-squares)))
375 (defmeth regression-model-proto :coef-estimates ()
376 "Message args: ()
377 Returns the OLS (ordinary least squares) estimates of the regression
378 coefficients. Entries beyond the intercept correspond to entries in basis."
379 (let ((n (array-dimension (send self :x) 1))
380 (indices (if (send self :intercept)
381 (cons 0 (+ 1 (send self :basis)))
382 (+ 1 (send self :basis))))
383 (m (send self :sweep-matrix)))
384 (coerce (compound-data-seq (select m (+ 1 n) indices)) 'list)))
386 (defmeth regression-model-proto :xtxinv ()
387 "Message args: ()
388 Returns ((X^T) X)^(-1) or ((X^T) W X)^(-1)."
389 (let ((indices (if (send self :intercept)
390 (cons 0 (1+ (send self :basis)))
391 (1+ (send self :basis)))))
392 (select (send self :sweep-matrix) indices indices)))
394 (defmeth regression-model-proto :coef-standard-errors ()
395 "Message args: ()
396 Returns estimated standard errors of coefficients. Entries beyond the
397 intercept correspond to entries in basis."
398 (let ((s (send self :sigma-hat)))
399 (if s (* (send self :sigma-hat) (sqrt (diagonal (send self :xtxinv)))))))
401 (defmeth regression-model-proto :studentized-residuals ()
402 "Message args: ()
403 Computes the internally studentized residuals for included cases and externally studentized residuals for excluded cases."
404 (let ((res (send self :residuals))
405 (lev (send self :leverages))
406 (sig (send self :sigma-hat))
407 (inc (send self :included)))
408 (if-else inc
409 (/ res (* sig (sqrt (pmax .00001 (- 1 lev)))))
410 (/ res (* sig (sqrt (+ 1 lev)))))))
412 (defmeth regression-model-proto :externally-studentized-residuals ()
413 "Message args: ()
414 Computes the externally studentized residuals."
415 (let* ((res (send self :studentized-residuals))
416 (df (send self :df)))
417 (if-else (send self :included)
418 (* res (sqrt (/ (- df 1) (- df (^ res 2)))))
419 res)))
421 (defmeth regression-model-proto :cooks-distances ()
422 "Message args: ()
423 Computes Cook's distances."
424 (let ((lev (send self :leverages))
425 (res (/ (^ (send self :studentized-residuals) 2)
426 (send self :num-coefs))))
427 (if-else (send self :included) (* res (/ lev (- 1 lev) )) (* res lev))))
430 (defun plot-points (x y &rest args)
431 "FIXME!!"
432 (error "Graphics not implemented yet."))
434 ;; Can not plot points yet!!
435 (defmeth regression-model-proto :plot-residuals (&optional x-values)
436 "Message args: (&optional x-values)
437 Opens a window with a plot of the residuals. If X-VALUES are not supplied
438 the fitted values are used. The plot can be linked to other plots with the
439 link-views function. Returns a plot object."
440 (plot-points (if x-values x-values (send self :fit-values))
441 (send self :residuals)
442 :title "Residual Plot"
443 :point-labels (send self :case-labels)))
445 (defmeth regression-model-proto :plot-bayes-residuals
446 (&optional x-values)
447 "Message args: (&optional x-values)
448 Opens a window with a plot of the standardized residuals and two standard
449 error bars for the posterior distribution of the actual deviations from the
450 line. See Chaloner and Brant. If X-VALUES are not supplied the fitted values
451 are used. The plot can be linked to other plots with the link-views function.
452 Returns a plot object."
453 (let* ((r (/ (send self :residuals) (send self :sigma-hat)))
454 (d (* 2 (sqrt (send self :leverages))))
455 (low (- r d))
456 (high (+ r d))
457 (x-values (if x-values x-values (send self :fit-values)))
458 (p (plot-points x-values r
459 :title "Bayes Residual Plot"
460 :point-labels (send self :case-labels))))
461 ;; AJR:FIXME
462 ;; the lambda needs to be something that fits into list
463 ;; (map 'list
464 ;; #'(lambda (a b c d) (send p :plotline a b c d nil))
465 ;; x-values low x-values high)
466 (send p :adjust-to-data)