4
$\begingroup$

I'm trying to fit two equations with nls() function in R. The two functions are:

$f(x) = c_{1} \exp\left(-\left(\frac{x-\mu}{\sigma_{(x)}}\right)^2\right)$

where $\sigma_{(x)} = \sigma_{11}$ if $x \le \mu$ and $\sigma_{(x)} = \sigma_{12}$ if $x > \mu$

and

$f(x) = a K \exp\left(- \frac{a}{b} \exp\left(-b x\right) - bx\right)$

Below is my attempt with factitious data:

x <- seq(from = 17, to = 47, by = 5)
y <- c(26.2, 173.6, 233.9, 185.9, 115.4, 62.0, 21.7)
Data <- data.frame(y, x)
Fit1 <- nls(formula =  y ~ if (x <= Mu) Mean <- c1*exp(-((x-Mu)/Sigma11)^2) else Mean     <- c1*exp(-((x-Mu)/Sigma12)^2),
                 data = Data, start = list(c1 = 240, Mu = 25, Sigma11 = 5, Sigma12 = 14), trace = TRUE)



Fit2 <- nls(formula =  y~K*a*exp(-(a/b)*exp(-b*x)-b*x), data = Data,
                start = list(K=4250, a=10, b=0.1), trace = TRUE)

Both codes produce Error and Warning messages. Any help to figure out these problems will be highly appreciated. Thanks

$\endgroup$
3
  • 3
    $\begingroup$ What are the messages? I would guess they are related to the nondifferentiability of the first model and the terrible starting values in the second. $\endgroup$
    – whuber
    Commented Jun 5, 2011 at 22:05
  • $\begingroup$ For first model the error message is Error in nlsModel(formula, mf, start, wts) : singular gradient matrix at initial parameter estimates; For the second model the Error message is: 133504.8 : 4250.0 10.0 0.1 Error in nls(formula = y ~ K * a * exp(-(a/b) * exp(-b * x) - b * x), : singular gradient $\endgroup$
    – MYaseen208
    Commented Jun 5, 2011 at 22:12
  • 1
    $\begingroup$ For the first problem, use an optimizer that does not assume differentiability. (There's a list of optimizers at cran.r-project.org/web/views/Optimization.html .) For the second, start with a better estimate. $\endgroup$
    – whuber
    Commented Jun 5, 2011 at 22:22

1 Answer 1

4
$\begingroup$

In the first case, nls will not digest any ifs or other higher expressions... you may use ifelse, however this may make this function too complex to effectively fit it -- nls is not a magic wand.

In the second case, the standard algorithm dies on numerical error -- the usual approach in this case is to alter starting point or change the used method; for instance

Fit2<-nls(y~K*a*exp(-(a/b)*exp(-b*x)-b*x),Data,
 start=list(K=4250,a=10,b=0.1),trace=T,algorithm="port")

do converge (consult ?nls for a list of methods).

$\endgroup$
1
  • $\begingroup$ Thanks a lot. Both models worked. Thanks again for your help. $\endgroup$
    – MYaseen208
    Commented Jun 5, 2011 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.