题
背景
使用r来预测系列中的下一个值。
问题
以下代码生成并绘制具有一定噪声的曲线模型:
slope = 0.55
offset = -0.5
amplitude = 0.22
frequency = 3
noise = 0.75
x <- seq( 0, 200 )
y <- offset + (slope * x / 100) + (amplitude * sin( frequency * x / 100 ))
yn <- y + (noise * runif( length( x ) ))
gam.object <- gam( yn ~ s( x ) + 0 )
plot( gam.object, col = rgb( 1.0, 0.392, 0.0 ) )
points( x, yn, col = rgb( 0.121, 0.247, 0.506 ) )
该模型揭示了预期的趋势。麻烦正在预测后续值:
p <- predict( gam.object, data.frame( x=201:210 ) )
绘制后,预测看起来不正确:
df <- data.frame( fit=c( fitted( gam.object ), p ) )
plot( seq( 1:211 ), df[,], col="blue" )
points( yn, col="orange" )
预测的值(从201开始)似乎太低了。
问题
- 如图所示,预测值实际上是最准确的预测吗?
- 如果没有,如何提高准确性?
- 是什么是连接两个数据集的更好方法(
fitted.values( gam.object )
和p
)?
解决方案
- 模拟数据很奇怪,因为您添加到“ True”的所有错误
y
大于0。(runif
创建数字[0,1]
, , 不是[-1,1]
.) - 当允许模型中的截距项时,问题就会消失。
例如:
gam.object2 <- gam( yn ~ s( x ))
p2 <- predict( gam.object2, data.frame( x=201:210 ))
points( 1:211, c( fitted( gam.object2 ), p2), col="green")
模型中系统地低估没有截距的原因可能是 gam
对估计的平滑函数使用和零约束。我认为第2点回答了您的第一个和第二个问题。
您的第三个问题需要澄清,因为 gam
- 对象不是 data.frame
. 。两种数据类型不混合。
一个更完整的示例:
slope = 0.55
amplitude = 0.22
frequency = 3
noise = 0.75
x <- 1:200
y <- (slope * x / 100) + (amplitude * sin( frequency * x / 100 ))
ynoise <- y + (noise * runif( length( x ) ))
gam.object <- gam( ynoise ~ s( x ) )
p <- predict( gam.object, data.frame( x = 1:210 ) )
plot( p, col = rgb( 0, 0.75, 0.2 ) )
points( x, ynoise, col = rgb( 0.121, 0.247, 0.506 ) )
points( fitted( gam.object ), col = rgb( 1.0, 0.392, 0.0 ) )
不隶属于 StackOverflow