我正在尝试对一些简单数据(按年计算的 Jade 米产量)执行非线性拟合。在 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 删除了趋势什么的。任何帮助都会很棒。
最佳答案
两个选项。正如 @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)
输出:
关于r - 关于 nls fit in R 的问题 - 为什么这如此奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64977367/