r - nls最合适的线-如何强制绘制线?

标签 r error-handling nls

我正在尝试编写一个基本函数,以便使用nls将一些最合适的线添加到绘图中。
除非数据恰好恰好是由传递给nls的公式精确定义的,否则这将正常工作。我知道了这些问题,并且这已记录为as reported here行为。

我的问题是,无论模型确切描述的数据如何,我如何绕开它并强制绘制一条最佳拟合线?有没有办法检测数据是否完全匹配并绘制出完美拟合的曲线?我当前躲闪的解决方案是:

#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)

有没有更好的办法?

最佳答案

Use 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 

关于r - nls最合适的线-如何强制绘制线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13945045/

相关文章:

sql - to_number Oracle SQL 中数字格式的动态长度

R 组合列表项

r - 如何获得椭圆的半轴长度?在 R

r - Skimr - 似乎无法生成直方图

c# - 在 javascript 中捕获从 C# Web 服务抛出的异常

oracle - JDBC 瘦驱动程序的 NLS_LANG 设置?

r - 使用 if else 条件将模型拟合到分组数据

php - 错误监控/处理/提醒系统中PHP服务的最佳实践

angular - auth0 授权 api 调用返回 200 状态但仍然得到错误响应

r - 如何为 nls 函数找到好的起始值?