【问题标题】:nls line of best fit - how to force plotting of line?nls 最佳拟合线 - 如何强制绘制线?
【发布时间】:2012-12-19 03:23:06
【问题描述】:

我正在尝试编写一个基本函数,以使用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)

有没有更好的办法?

【问题讨论】:

  • 尽管如此,在现实世界中,这种情况永远不会发生。总是有测量误差。除非你是一名正在参加 R 考试并为你的学生提供完美数据集的老师,否则就是:-)。
  • @CarlWitthoft 如果 n 很小,我在从 Excel 导出为 CSV 的数据(因此四舍五入为可见数字)时遇到了这种问题。
  • @Roland,我想如果你不恰当地四舍五入你的测试数据(即丢失有效的无花果),你会得到你应得的:-)
  • @CarlWitthoft 好吧,如果您进行适合测量精度的四舍五入,然后使用 n=4 进行回归(不应该这样做,但这就是生活)...

标签: r error-handling nls


【解决方案1】:

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 

【讨论】:

    猜你喜欢
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 2018-06-04
    • 2022-11-04
    • 1970-01-01
    • 2021-03-15
    相关资源
    最近更新 更多