简体   繁体   English

在r中进行非线性最小二乘拟合

[英]do a nonlinear least square fit in r

I have two vectors: 我有两个向量:

y <- c(0.044924, 0.00564, 0.003848, 0.002385, 0.001448, 0.001138, 
0.001025, 0.000983, 0.00079, 0.000765, 0.000721, 0.00061, 0.000606, 
0.000699, 0.000883, 0.001069, 0.001226, 0.001433, 0.00162, 0.001685, 
0.001604, 0.001674, 0.001706, 0.001683, 0.001505, 0.001497, 0.001416, 
0.001449, 0.001494, 0.001544, 0.00142, 0.001458, 0.001544, 0.001279, 
0.00159, 0.001756, 0.001749, 0.001909, 0.001885, 0.002063, 0.002265, 
0.002137, 0.002391, 0.002619, 0.002733, 0.002957, 0.003244, 0.003407, 
0.003563, 0.003889, 0.004312, 0.004459, 0.004946, 0.005248, 0.005302, 
0.00574, 0.006141, 0.006977, 0.007386, 0.007843, 0.008473, 0.008949, 
0.010164, 0.010625, 0.011279, 0.01191, 0.012762, 0.014539, 0.01477)

x <- 0:68

I am trying to use the non-linear least squares function to fit the data but I keep getting the error: 我试图使用非线性最小二乘函数来拟合数据但我不断得到错误:

Error in nlsModel(formula, mf, start, wts) : singular gradient matrix at initial parameter estimates nlsModel中的错误(公式,mf,start,wts):初始参数估计时的奇异梯度矩阵

My code is: 我的代码是:

a=0.00012
b=0.08436
k=0.21108
fit = nls(y ~ (a*b*exp(b*x)*k)/((k*b)+(a*(exp(b*x)-1))), start=list(a=a,b=b,k=k))

The parameters I have entered are parameters that I know are close to the expected values. 我输入的参数是我知道的接近预期值的参数。 Does anyone know what am I doing wrong here? 有谁知道我在这里做错了什么?

I have tried various initial values for the parameters a , b and k , but I always get some kind of error. 我已经尝试了参数abk各种初始值,但我总是遇到某种错误。

Use optim() instead. 请改用optim() You have to make a function which takes a,b and k as input (collected as a vector), and which returns the squared error as a result: 你必须创建一个函数,它将a,b和k作为输入(作为向量收集),并返回平方误差作为结果:

func <-function(pars) {
  a <- pars["a"]
  b <- pars["b"]
  k <- pars["k"]
  fitted <- (a*b*exp(b*x)*k)/((k*b)+(a*(exp(b*x)-1)))
  sum((y-fitted)^2)  
  } 

Then we run optim() using the initial values: 然后我们使用初始值运行optim():

result <- optim(c(a=0.00012, b=0.08436, k=0.21108), func)

To test the resulting fit: 为了测试最终的拟合:

plot(x, y)
a <- result$par["a"]
b <- result$par["b"]
k <- result$par["k"]
lines((a*b*exp(b*x)*k)/((k*b)+(a*(exp(b*x)-1))), col = "blue")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM