关于 nls fit in R 的问题 - 为什么这如此奇怪?

Question on nls fit in R - why is this such a strange fit?

我正在尝试对一些简单数据(按年计算的玉米产量)执行非线性拟合。用 R 中的 lm 来做就足够直接了,但是如果允许曲线的话,一些数据会更适合,大约 year^1.5 左右。

x <- c(1979L, 1980L, 1981L, 1982L, 1983L, 1984L, 1985L, 1986L, 1987L, 
1988L, 1989L, 1990L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 
1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 
2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 2012L, 2013L, 2015L, 
2016L, 2017L, 2018L, 2019L)

y <- c(47.3, 25.4, 39, 56.4, 41.4, 56.1, 60.3, 58, 64, 35, 56, 54, 
37, 80, 59, 88, 55, 87, 90, 99, 93, 90.4, 80.7, 35, 80.2, 104.9, 
59.9, 43.5, 97.9, 106, 132, 121.7, 120.1, 63.9, 142.5, 129.9, 
114.8, 122.1, 164.3, 133.9)

yield_model <- nls(y ~ x^a,start=list(a = 1))

plot(x,y)
lines(x,predict(yield_model),lty=2,col="red",lwd=3)

> yield_model2
Nonlinear regression model
 model: y ~ x^a
 data: parent.frame()
 a 
0.5778 
residual sum-of-squares: 46984

Number of iterations to convergence: 8 
Achieved convergence tolerance: 7.566e-09

为什么 nls 拟合得这么差(如果你绘制它就可以看到)?我做错什么了吗?您可以想象,与数据拟合的轻微曲线以及趋势会更好。就像 nls 删除了趋势什么的。任何帮助都会很棒。

拟合忘记了常数项,即 y 截距。与其他建模函数不同,nls 需要显式拦截。
下面我也用lm拟合了一个线性模型,用于比较

df1 <- data.frame(x, y)

yield_model <- nls(y ~ k + x^a, data = df1, start=list(k = 0, a = 1))
yield_model2 <- lm(y ~ x, df1)
summary(yield_model)
summary(yield_model2)

plot(x, y)
lines(x, predict(yield_model), lty = "dashed", col = "red", lwd = 3)
lines(x, predict(yield_model2), lty = "dotted", col = "blue", lwd = 3)

如您所见,拟合度非常接近。但是他们不相等,看看吧运行:

predict(yield_model) - predict(yield_model2)

两种选择。正如 @RuiBarradas 所提到的,问题在于模型的规格。您可以使用 lm() 设置起始值,如下所示:

#Define initial values
mod <- lm(y~x)
#nls model
yield_model <- nls(y ~ a+x^b,
                   start=list(a = mod$coefficients[1],b=mod$coefficients[2]))
#Plot
plot(x,y)
lines(x,predict(yield_model),lty=2,col="red",lwd=3)

输出:

或尝试另一种方法 loess:

library(ggplot2)
#Data
df <- data.frame(x=x,y=y)
#Plot
ggplot(df,aes(x=x,y=y))+
  geom_point()+
  stat_smooth(se=F)

输出: