1

我正在尝试编写一个基本函数来添加一些最适合使用nls. 除非数据恰好由传递给nls. 我知道这些问题,并且这是此处报告的记录行为。

但我的问题是,无论模型准确描述的数据如何,我如何才能解决这个问题并强制绘制一条最佳拟合线?有没有办法检测数据完全匹配并绘制完美拟合曲线?我目前的狡猾的解决方案是:

#test data
x <- 1:10
y <- x^2
plot(x, y, pch=20)

# polynomial line of best fit
f <- function(x,a,b,d) {(a*x^2) + (b*x) + d}
fit <- nls(y ~ f(x,a,b,d), start = c(a=1, b=1, d=1)) 
co <- coef(fit)
curve(f(x, a=co[1], b=co[2], d=co[3]), add = TRUE, col="red", lwd=2) 

失败并出现错误:

Error in nls(y ~ f(x, a, b, d), start = c(a = 1, b = 1, d = 1)) : 
  singular gradient

我应用的简单修复方法是jitter稍微处理数据,但这似乎有点破坏性和骇人听闻。

# the above code works after doing...
y <- jitter(x^2)

有没有更好的办法?

4

1 回答 1

6

使用 Levenberg-Marquardt

x <- 1:10
y <- x^2

f <- function(x,a,b,d) {(a*x^2) + (b*x) + d}
fit <- nls(y ~ f(x,a,b,d), start = c(a=1, b=0, d=0)) 

Error in nls(y ~ f(x, a, b, d), start = c(a = 1, b = 0, d = 0)) : 
  number of iterations exceeded maximum of 50

library(minpack.lm)
fit <- nlsLM(y ~ f(x,a,b,d), start = c(a=1, b=0, d=0))
summary(fit)

Formula: y ~ f(x, a, b, d)

Parameters:
  Estimate Std. Error t value Pr(>|t|)    
a        1          0     Inf   <2e-16 ***
b        0          0      NA       NA    
d        0          0      NA       NA    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 0 on 7 degrees of freedom

Number of iterations to convergence: 1 
Achieved convergence tolerance: 1.49e-08

请注意,我必须调整起始值,结果对起始值很敏感。

fit <- nlsLM(y ~ f(x,a,b,d), start = c(a=1, b=0.1, d=0.1))

Parameters:
    Estimate Std. Error    t value Pr(>|t|)    
a  1.000e+00  2.083e-09  4.800e+08  < 2e-16 ***
b -7.693e-08  1.491e-08 -5.160e+00  0.00131 ** 
d  1.450e-07  1.412e-08  1.027e+01  1.8e-05 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 6.191e-08 on 7 degrees of freedom

Number of iterations to convergence: 3 
Achieved convergence tolerance: 1.49e-08 
于 2012-12-19T08:13:50.593 回答