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
8 ;;;; XLISP-STAT 2.1 Copyright (c) 1990, by Luke Tierney
9 ;;;; Additions to Xlisp 2.1, Copyright (c) 1989 by David Michael Betz
10 ;;;; You may give out copies of this software; for conditions see the file
11 ;;;; COPYING included with this distribution.
13 (defpackage :lisp-stat-regression-nonlin
15 :lisp-stat-object-system
18 :lisp-stat-compound-data
21 :lisp-stat-regression-linear
)
22 (:shadowing-import-from
:lisp-stat-object-system
23 slot-value call-method call-next-method
)
24 (:shadowing-import-from
:lisp-stat-math
25 expt
+ -
* / ** mod rem abs
1+ 1- log exp sqrt sin cos tan
26 asin acos atan sinh cosh tanh asinh acosh atanh float random
27 truncate floor ceiling round minusp zerop plusp evenp oddp
28 < <= = /= >= > complex conjugate realpart imagpart phase
29 min max logand logior logxor lognot ffloor fceiling
30 ftruncate fround signum cis
)
32 (:export nreg-model nreg-model-proto mean-function theta-hat epsilon
35 (in-package :lisp-stat-regression-nonlin
)
38 ;;; Nonlinear Regression Model Prototype
41 (defproto nreg-model-proto
42 '(mean-function theta-hat epsilon count-limit verbose
)
44 regression-model-proto
)
46 (defun nreg-model (mean-function y theta
57 "Args: (mean-function y theta &key (epsilon .0001) (count-limit 20)
58 (print t) parameter-names response-name case-labels
59 weights included (vetbose print))
60 Fits nonlinear regression model with MEAN-FUNCTION and response Y using initial
61 parameter guess THETA. Returns model object."
62 (let ((m (send nreg-model-proto
:new
)))
63 (send m
:mean-function mean-function
)
65 (send m
:new-initial-guess theta
)
66 (send m
:epsilon epsilon
)
67 (send m
:count-limit count-limit
)
68 (send m
:parameter-names parameter-names
)
69 (send m
:response-name response-name
)
70 (send m
:case-labels case-labels
)
71 (send m
:weights weights
)
72 (send m
:included included
)
73 (send m
:verbose verbose
)
74 (if print
(send m
:display
))
77 (defmeth nreg-model-proto
:save
()
79 Returns an expression that will reconstruct the regression model."
80 `(nreg-model ',(send self
:mean-function
)
82 ',(send self
:coef-estimates
)
83 :epsilon
',(send self
:epsilon
)
84 :count-limit
',(send self
:count-limit
)
85 :predictor-names
',(send self
:predictor-names
)
86 :response-name
',(send self
:response-name
)
87 :case-labels
',(send self
:case-labels
)
88 :weights
',(send self
:weights
)
89 :included
',(send self
:included
)
90 :verbose
',(send self
:verbose
)))
96 (defmeth nreg-model-proto
:compute
()
98 Recomputes the estimates. For internal use by other messages"
99 (let* ((y (send self
:y
))
100 (weights (send self
:weights
))
101 (inc (if-else (send self
:included
) 1 0))
102 (w (if weights
(* inc weights
) inc
)))
103 (setf (slot-value 'theta-hat
)
104 (nlreg (send self
:mean-function
)
106 (slot-value 'theta-hat
)
108 (send self
:count-limit
)
110 (send self
:verbose
)))
111 (setf (slot-value 'x
)
112 (funcall (make-jacobian (slot-value 'mean-function
)
113 (length (slot-value 'theta-hat
)))
114 (slot-value 'theta-hat
)))
115 (setf (slot-value 'intercept
) nil
)
117 (let ((r (send self
:residuals
)))
118 (setf (slot-value 'residual-sum-of-squares
)
119 (sum (* inc r r
))))))
122 ;;; Slot Accessors and Mutators
125 (defmeth nreg-model-proto
:new-initial-guess
(guess)
126 "Message args: (guess)
127 Sets a new initial uess for parmeters."
128 (setf (slot-value 'theta-hat
) guess
)
129 (send self
:needs-computing t
))
131 (defmeth nreg-model-proto
:theta-hat
()
133 Returns current parameter estimate."
134 (if (send self
:needs-computing
) (send self
:compute
))
135 (coerce (slot-value 'theta-hat
) 'list
))
137 (defmeth nreg-model-proto
:mean-function
(&optional f
)
138 "Message args: (&optional f)
139 With no argument returns the mean function as supplied to m. With an
140 argument F sets the mean function of m to F and recomputes the
142 (when (and f
(functionp f
))
143 (setf (slot-value 'mean-function
) f
)
144 (send self
:needs-computing t
))
145 (slot-value 'mean-function
))
147 (defmeth nreg-model-proto
:epsilon
(&optional eps
)
148 "Message args: (&optional eps)
149 With no argument returns the tolerance as supplied to m. With an argument
150 EPS sets the tolerance of m to EPS and recomputes the estimates."
151 (when (and eps
(numberp eps
))
152 (setf (slot-value 'epsilon
) eps
)
153 (send self
:needs-computing t
))
154 (slot-value 'epsilon
))
156 (defmeth nreg-model-proto
:count-limit
(&optional count
)
157 "Message args: (&optional new-count)
158 With no argument returns the iteration count limit as supplied to m. With
159 an argument COUNT sets the limit to COUNT and recomputes the
161 (when (and count
(numberp count
))
162 (setf (slot-value 'count-limit
) count
)
163 (send self
:needs-computing t
))
164 (slot-value 'count-limit
))
166 (defmeth nreg-model-proto
:parameter-names
(&optional
(names nil set
))
167 "Method args: (&optional names)
168 Sets or returns parameter names."
169 (if set
(setf (slot-value 'predictor-names
) names
))
170 (let ((p-names (slot-value 'predictor-names
))
171 (p (length (slot-value 'theta-hat
))))
172 (if (not (and p-names
(= p
(length p-names
))))
173 (setf (slot-value 'predictor-names
)
174 (mapcar #'(lambda (a) (format nil
"Parameter ~a" a
))
176 (slot-value 'predictor-names
))
178 (defmeth nreg-model-proto
:verbose
(&optional
(val nil set
))
179 "Method args: (&optional val)
180 Sets or retrieves verbose setting. If T iteration info is printed during
182 (if set
(setf (slot-value 'verbose
) val
))
183 (slot-value 'verbose
))
186 ;;; Overrides for Linear Regression Methods
189 (defmeth nreg-model-proto
:x
()
191 Returns the Jacobian matrix at theta-hat."
194 (defmeth nreg-model-proto
:intercept
(&rest args
)
196 Always returns nil. (For compatibility with linear regression.)"
199 (defmeth nreg-model-proto
:fit-values
()
201 Returns the fitted values for the model."
202 (coerce (funcall (send self
:mean-function
) (send self
:theta-hat
))
205 (defmeth nreg-model-proto
:coef-estimates
(&optional guess
)
206 "Message args: (&optional guess)
207 With no argument returns the current parameter estimate. With an
208 argument GUESS takes it as a new initial guess and recomputes
210 (if guess
(send self
:new-initial-guess guess
))
211 (send self
:theta-hat
))
213 (defmeth nreg-model-proto
:predictor-names
() (send self
:parameter-names
))
217 ;;;; Linear Regression Coefficients
221 (defun regression-coefficients (x y
&key
(intercept T
) weights
)
222 "Args: (x y &key (intercept T) weights)
223 Returns the coefficients of the regression of the sequence Y on the columns of
225 (let* ((m (if weights
226 (make-sweep-matrix x y weights
)
227 (make-sweep-matrix x y
)))
228 (n (array-dimension x
1)))
229 (coerce (compound-data-seq
231 (select (car (sweep-operator m
(iseq 1 n
)))
234 (select (car (sweep-operator m
(iseq 0 n
)))
241 ;;;; Nonlinear Regression Functions
244 (defun nlreg1 (f j y initial-beta epsilon count-limit weights verbose
)
245 "Args: (mean-function jacobian y initial-beta
246 epsilon count-limit weights verbose)
247 MEAN-FUNCTION returns the mean response vector for a given parameter vector.
248 JACOBIAN returns the jacobian of MEAN-FUNCTION at a given parameter vector.
249 Y is the observed response vector. Returns the estimated parameter vector
250 obtained by a Gauss-Newton algorithm with backtracking that continues until
251 the COUNT-LIMIT is reached or no component of the parameter vector changes
252 by more than EPSILON."
253 (labels ((rss (beta) ; residual sum of squares
254 (let ((res (- y
(funcall f beta
))))
255 (sum (if weights
(* res res weights
) (* res res
)))))
256 (next-beta (beta delta rss
) ; next beta by backtracking
257 (do* ((lambda 1 (/ lambda
2))
258 (new-rss (rss (+ beta delta
))
259 (rss (+ beta
(* lambda delta
)))))
260 ((or (< new-rss rss
) (< lambda
.0001))
261 (if (>= lambda
.0001)
262 (+ beta
(* lambda delta
))
264 (do* ((delbeta (regression-coefficients
265 (funcall j initial-beta
)
266 (- y
(funcall f initial-beta
))
269 (regression-coefficients
271 (- y
(funcall f beta
))
274 (beta initial-beta
(next-beta beta delbeta rss
))
275 (rss (rss beta
) (rss beta
))
276 (count 0 (1+ count
)))
277 ((or (> count count-limit
) (> epsilon
(max (abs delbeta
))))
278 (if (and verbose
(> count count-limit
))
279 (format t
"Iteration limit exceeded.~%"))
281 (if verbose
(format t
"Residual sum of squares: ~10g~%" rss
)))))
283 (defun make-jacobian (f n
)
285 F is a function of an N-vector. Returns a function that approximates the
286 jacobian function iof F by a symmetric difference."
288 (del (* h
(values-list (column-list (identity-matrix n
))))))
290 (let ((b+ (mapcar #'(lambda (x) (+ b x
)) del
))
291 (b- (mapcar #'(lambda (x) (- b x
)) del
)))
292 ;; FIXME:AJR BAD IDIOM FOLLOWS
293 (apply #'bind-columns
(/ (- (mapcar f b
+) (mapcar f b-
)) (* 2 h
)))))))
295 (defun nlreg (f y guess
&optional
296 (epsilon .0001) (count-limit 20) weights verbose
)
297 "Args: (mean-function y guess &optional
298 (epsilon .0001) (count-limit 20) weights verbose)
299 MEAN-FUNCTION returns the mean response vector for a given parameter vector.
300 Y is the observed response vector. Returns the estimated parameter vector
301 obtained by a Gauss-Newton algorithm that continues until the ITERATION-LIMIT
302 is reached or no component of the parameter vector changes by more than
303 EPSILON. The jacobian of MEAN-FUNCTION is approximated by a symmetric difference."
304 (nlreg1 f
(make-jacobian f
(length guess
)) y guess
305 epsilon count-limit weights verbose
))