nlsがRに適合することに関する質問-なぜこれがそのような奇妙な適合なのですか?
Nov 23 2020
いくつかの単純なデータ(年ごとのトウモロコシの収穫量)に非線形フィットを実行しようとしています。Rのlmでそれを行うのは簡単ですが、年^ 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がトレンドか何かを削除したようなものです。どんな助けでも素晴らしいでしょう。
回答
3 Duck Nov 23 2020 at 22:51
2つのオプション。@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)
出力:

2 RuiBarradas Nov 23 2020 at 22:41
近似は定数項、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)