user1402050
user1402050

Reputation: 23

R nls gaussian fit "singular gradient matrix at initial parameter estimates"

I tried to fit my data with a gaussian curve using nls. Because that didn't work, i tried to make an easy example to see what goes wrong:

>x=seq(-4,4,0.1)
>y=2*dnorm(x-0.4,2)+runif( length(x) , min = -0.01, max = 0.01)
>df=data.frame(x,y)
>m <- nls(y ~ k*dnorm(x-mu,sigma), data = df, start = list(k=2,mu=0.4,sigma=2))

Error in nlsModel(formula, mf, start, wts, upper) :   singular gradient 
matrix at initial parameter estimates
> m <- nls(y ~ k*dnorm(x-mu,sigma), data = df, start == list(k=1.5,mu=0.4,sigma=2))

Error in nlsModel(formula, mf, start, wts, upper) :   singular gradient 
matrix at initial parameter estimates

Why doesn't this work?

Upvotes: 1

Views: 2541

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269441

First please use set.seed to make your example reproducible. Second I think you meant dnorm(x, 0.4, 2) and not dnorm(x-0.4, 2). These are not the same since in the x-0.4 case the mean of x-0.4 is 2 and in the other case the standard devaiation is 2. If we make this change then it works:

set.seed(123)
x=seq(-4,4,0.1)
y=2*dnorm(x, 0.4, 2)+runif( length(x) , min = -0.01, max = 0.01)
df=data.frame(x,y)
nls(y ~ k*dnorm(x, mu,sigma), data = df, start = list(k=2,mu=0.4,sigma=2))

giving:

Nonlinear regression model
  model: y ~ k * dnorm(x, mu, sigma)
   data: df
     k     mu  sigma 
2.0034 0.3914 2.0135 
 residual sum-of-squares: 0.002434

Number of iterations to convergence: 2 
Achieved convergence tolerance: 5.377e-06

Upvotes: 1

Related Questions