Why does the "nls" function of R not converge even with the initial curve very close to the points?

Asked

Viewed 38 times

2

To adjust the following points with the function whose initial kick is represented by the line:

Pontos com curva inicial para ajuste.

But I get the following message:

Error in nls(y ~ A * (1 + erf(E * B * (x - C)/sqrt(2))) * dnorm(B * (x - : gradiente singular
Traceback:

1. nls(y ~ A * (1 + erf(E * B * (x - C)/sqrt(2))) * dnorm(B * (x - 
 .     C)) + D, data = fdata, start = list(A = A0, B = B0, C = C0, 
 .     D = D0, E = E0))

This is my code:

erf <- function(x) 2 * pnorm(x * sqrt(2)) - 1

x = c(0.275, 0.325, 0.375, 0.425, 0.475, 0.525, 0.575, 0.625, 0.675, 0.725, 0.775, 0.825, 0.875, 0.925, 0.975)
y = c(33, 69, 48, 57, 51, 46, 36, 42, 26, 22, 22, 18, 16, 9, 5)

plot(x, y, xlim=c(0,1))

fdata = data.frame(x = x, y = y)

# Initial parameter values:
A0 = 1.3*max(y); B0 = 3.8*max(x); C0 = 1.0*x[which.max(y)]; D0 = 0.0; E0 = 4.0

# Plot curve with initial parameter values:
xfit0 = seq(from=0.0, to=1.0, length.out=100)
yfit0 = A0*(1+erf(E0*B0*(xfit0-C0)/sqrt(2)))*dnorm(B0*(xfit0-C0))+D0
lines(xfit0, yfit0, lwd=3)

# Do the fit:
fit <- nls(y~A*(1+erf(E*B*(x-C)/sqrt(2)))*dnorm(B*(x-C))+D, data = fdata, start = list(A = A0, B = B0, C = C0, D = D0, E = E0))
lines(fdata$x, predict(fit), col="red", lwd=2)

Why the nls does not show convergence? The algorithm would be less tolerant? It is possible to configure it to accept a greater deviation as acceptable?

  • It has 5 parameters and 15 points, seems to be very little.

1 answer

3


The problem lies in the excess of parameters for so few points.

If the function to be adjusted is using a translation of the x-axis represented by x - C, one of the parameters can be deleted, C, adjusting the function with values of x1 = x - C0.

fdata$x1 <- fdata$x - C0

fit1 <- nls(y ~ A*(1 + erf(E*B*x1/sqrt(2)))*dnorm(B*x1) + D, 
           data = fdata, 
           start = list(A = A0, B = B0, D = D0, E = E0))


lines(fdata$x, predict(fit1), col="red", lwd=2)

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.