简体   繁体   English

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

[英]Nonlinear least squares curve fitting in R

I am new to R (first time using it). 我是R的新手(第一次使用它)。 and I am following this tutorial http://www.walkingrandomly.com/?p=5254 to try to plot a curve and discover the function that best fits my data. 我正在按照本教程http://www.walkingrandomly.com/?p=5254尝试绘制曲线并发现最适合我数据的函数。 So far I have tryed: 到目前为止,我尝试过:

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

So I get this: 所以我明白了:

在此输入图像描述

Then I try: 然后我尝试:

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

And I get this error: 我收到这个错误:

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

What am I doing wrong? 我究竟做错了什么? Thanks 谢谢

The nls function does not automatically include coefficients for all of your parameters in the model. nls函数不会自动包含模型中所有参数的系数。 You must explicitly include them in the formula. 您必须在公式中明确包含它们。 I'm not exactly sure where you wanted p1 and p2 to be included in the model from your description 我不确定您希望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

but at least in this form this is still a linear model. 但至少在这种形式下,这仍然是一个线性模型。 You can get the same fit with 你可以得到同样的契合

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

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

For completeness, you can include Senor O solution within ggplot2 framework to get a plot of the smoothed solution and check the solution graphically: 为了完整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))

在此输入图像描述

You have no parameters in your formula. 您的公式中没有参数。 You need to include them however you see fit: 你需要包括它们,但你认为合适:

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