繁体   English   中英

R中的非线性最小二乘曲线拟合

[英]Nonlinear least squares curve fitting in R

我是R的新手(第一次使用它)。 我正在按照本教程http://www.walkingrandomly.com/?p=5254尝试绘制曲线并发现最适合我数据的函数。 到目前为止,我尝试过:

> xdata = c(1 ,5, 10, 20, 100)
> ydata = c(23.83333333, 210.3666667, 545.3666667, 1756.866667, 38595.7)
> plot(xdata,ydata)

所以我明白了:

在此输入图像描述

然后我尝试:

> p1 = 1
> p2 = 0.2
> fit = nls(ydata ~ xdata^2, start=list(p1=p1,p2=p2))

我收到这个错误:

Error in nlsModel(formula, mf, start, wts) : 
  singular gradient matrix at initial parameter estimates

我究竟做错了什么? 谢谢

nls函数不会自动包含模型中所有参数的系数。 您必须在公式中明确包含它们。 我不确定您希望p1p2在您的描述中包含在模型中

p1 <- 1
p2 <- 0.2
fit <- nls(ydata ~ p1+p2*xdata^2, start=list(p1=p1,p2=p2))
fit

# Nonlinear regression model
#   model: ydata ~ p1 + p2 * xdata^2
#    data: parent.frame()
#      p1      p2 
# 127.216   3.847 
#  residual sum-of-squares: 21037
# 
# Number of iterations to convergence: 1 
# Achieved convergence tolerance: 5.774e-08

但至少在这种形式下,这仍然是一个线性模型。 你可以得到同样的契合

fit2 <- lm(ydata ~ I(xdata^2))
fit2

# Call:
# lm(formula = ydata ~ I(xdata^2))
# 
# Coefficients:
# (Intercept)   I(xdata^2)  
#     127.216        3.847  

为了完整ggplot2 ,您可以在ggplot2框架中包含Senor O解决方案,以获得平滑解决方案的图并以图形方式检查解决方案:

library(ggplot2)
ggplot(dat,aes(x=xdata,y=ydata)) +
   geom_point() +
   geom_smooth(method="nls", formula=y ~ p1+p2*x^2, se=FALSE, 
               start=list(p1=p1,p2=p2))

在此输入图像描述

您的公式中没有参数。 你需要包括它们,但你认为合适:

nls(ydata ~ p1 * xdata^2 + p2, start=list(p1=p1,p2=p2))

暂无
暂无

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

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