R - 初始参数估计时的奇异梯度矩阵

时间:2021-03-26 09:25:10

标签: r nls

我正在尝试将谐波方程拟合到我的数据中,但是当我应用 nls 函数时,R 给了我以下错误:

<块引用>

nlsModel(formula, mf, start, wts) 中的错误:初始参数估计时的奇异梯度矩阵。

我看到的所有与此错误相关的帖子都是指数函数,其中使用线性化来修复此错误,但在这种情况下,我无法以这种方式解决它。我尝试使用其他起点,但仍然无效。

代码:

y <- c(20.91676, 20.65219, 20.39272, 20.58692, 21.64712, 23.30965, 23.35657, 24.22724, 24.83439, 24.34865, 23.13173, 21.96117)
t <- c(1, 2, 3, 4 , 5 , 6, 7, 8, 9, 10, 11, 12)


# Fitting function

fit <- function(x, a, b, c) {a+b*sin(2*pi*x)+c*cos(2*pi*x)}

res <- nls(y ~ fit(t, a, b, c), data=data.frame(t,y), start = list(a=1,b=0, c=1))

你能帮我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

有几个问题:

  1. cos(2*pi*t) 是问题中给出的 t 的所有向量,因此模型无法识别,因为已经存在截距

  2. 该模型的参数是线性的,因此可以使用 lm 而不是 nls,并且不需要起始值

  3. 即使我们解决了大第二个系数所看到的那些点,该模型也不能很好地工作。改进模型。

lm(y ~ sin(2*pi*t))

给予:

Call:
lm(formula = y ~ sin(2 * pi * t))

Coefficients:
    (Intercept)  sin(2 * pi * t)  
      2.195e+01       -2.262e+14  

而是使用 plinear 算法尝试此模型,该算法不需要线性输入的参数的起始值。这实现了模型 .lin1 + .lin2 * cos(a * t + b),其中 .lin1 和 .lin2 参数是线性输入且不需要起始值的隐式参数。

fm <- nls(y ~ cbind(1, cos(a * t + b)), start = list(a = 1, b = 1), alg = "plinear")

plot(y ~ t)
lines(fitted(fm) ~ t, col = "red")

fm

给予:

Nonlinear regression model
  model: y ~ cbind(1, cos(a * t + b))
   data: parent.frame()
      a       b   .lin1   .lin2 
 0.5226  4.8814 22.4454 -2.1530 
 residual sum-of-squares: 0.7947

Number of iterations to convergence: 9 
Achieved convergence tolerance: 8.865e-06

screenshot

相关问题