StanLe
StanLe

Reputation: 5137

Dealing with 0 error in nls - R script

Is there any way to allow my nls to have 0 residual error when it makes a non linear fit? I have cases in my data where the fit made should have 0 error, but nls always fails and spits out an error.

Can anyone show me:

  1. How do I test if this is the error being spit out by nls?
  2. How to allow for 0 error cases? (Perfect fits)

This is my nls call:

fit <- nls(y ~ ifelse(g, m1 * (x - x0) + y0, m2 * (x - x0) + y0),
            start = c(m1 = -1, m2 = 1, y0 = 0, x0 = split),
            algorithm = "port",
            lower = c(m1 = -Inf, m2 = -Inf, y0 = -Inf, x0 = split),
            upper = c(m1 = Inf, m2 = Inf, y0 = Inf, x0 = (split+1)),
            data=data.frame(x,y))

Upvotes: 3

Views: 996

Answers (1)

joran
joran

Reputation: 173547

As mentioned in a previous answer, ?nls explicitly states that you should not use nls for 0 error data. To directly quote the help file for the function you are using:

Do not use nls on artificial "zero-residual" data.

The nls function uses a relative-offset convergence criterion that compares the numerical imprecision at the current parameter estimates to the residual sum-of-squares. This performs well on data of the form

y = f(x, θ) + eps

(with var(eps) > 0). It fails to indicate convergence on data of the form

y = f(x, θ)

because the criterion amounts to comparing two components of the round-off error. If you wish to test nls on artificial data please add a noise component, as shown in the example below.

A potentially dangerous option would be to use warnOnly = TRUE to force nls to return prior to convergence with a warning only (no error):

x <- -(1:100)/10
y <- 100 + 10 * exp(x / 2)
nlmod <- nls(y ~  Const + A * exp(B * x),control = nls.control(warnOnly = TRUE))

The above example was also taken nearly directly from ?nls.

Upvotes: 6

Related Questions