代码之家  ›  专栏  ›  技术社区  ›  aaronmams

我可以用GAMM估计R中随时间变化的季节效应吗?

  •  3
  • aaronmams  · 技术社区  · 8 年前

    我想用一个广义加性模型来研究R中的时间序列数据。我的数据是每月的,我想估计季节效应和长期趋势效应。我关注了加文·辛普森的一些有用帖子 here here :

    我的数据如下所示:

    trips

    我的github上有完整的数据集 page :

    我试图指定一个具有平滑季节和趋势项的广义相加模型,如下所示:

        df <- read.csv('trips.csv')
        head(df)
        # A tibble: 276 × 2
         date ntrips
       <date>  <int>
        1  1994-01-01    157
        2  1994-02-01    169
        3  1994-03-01    195
        4  1994-04-01    124
        5  1994-05-01    169
    
        #add a time column
        trips <- tbl_df(trips) %>% mutate(time=as.numeric(date))
    
        mod1 <- gamm(ntrips~s(month,bs="cc",k=12) + s(time),data=trips)
    

    我对季节效应的估计如下:

        pred <- predict(mod1$gam,newdata=trips,type="terms")
        seas <- data.frame(s=pred[,1],date=trips$date)
        ggplot(seas,aes(x=date,y=s)) + geom_line()
    

    该图包括以下内容:

    gam seasonals

    these 数据使用克利夫兰等人的STL方法:

    使用STL范式,摇摆或平滑程度如何允许季节性效应似乎是一个偏好或选择的问题。如果我能让数据告诉我随机误差和季节性峰值移动之间的差异,我会更喜欢。GAM似乎更适合这一目标,因为它们更容易进行统计模型拟合类型的练习。。。但我想知道R包中是否有一个参数用于拟合GAM,允许时变季节效应。

    1 回复  |  直到 8 年前
        1
  •  4
  •   Gavin Simpson    8 年前

    答案是:是的,可以为您感兴趣的问题制定GAM模型。如果我们假设模型的趋势和季节成分平滑地相互作用,我们就得到了连续相互作用的平滑等价物。可以使用两个边缘平滑的张量积在GAM中拟合这种相互作用:

    1. 季节性循环平滑,以及
    2. 长期趋势平稳

    顺便提一句,我还有更多关于这些的博客帖子:

    ## fix the knots are just passed the ends of the month numbers
    ## this allows Dec and Jan to have their own estimates
    knots <- list(month = c(0.5, 12.5))
    
    ## original model, fixed seasonal component
    m1 <- gam(ntrips ~ s(month, bs="cc", k=12) + s(time), data = trips,
              knots = knots)
    
    ## modified model with
    m2a <- gam(ntrips ~ te(month, time, bs = c("cc","tp"), k = c(12, 10)), data = trips,
              knots = knots))
    

    第二个模型的替代方法是对两个主要影响加上相互作用进行类似ANOVA的分解。在上面的修改模型中,所有三个分量都绑定在单张量积平滑中 te() 模型的一部分。

    类方差分析分解变量将使用

    m2b <- gam(ntrips ~ ti(month, bs = 'cc', k = 12) +
                 ti(time, bs = 'tp', k = 10) +
                 ti(month, time, bs = c("cc","tp")), data = trips,
               knots = knots)
    

    第三个 ti() 然后是平滑交互,从季节和长期趋势的主要平滑效果中分离出来。

    我已经展示了使用 gam() 但它们可以与 gamm()