How to construct a spline model using ulam()

Open
#415 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
25/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
r
Domain
data

Research direction

Start by reproducing the m4.7 spline model from the issue with ulam() and inspecting the generated Stan code, where B %*% w is translated into a loop over the 10751-length mu instead of the 827 rows of B. The problem is in how the R-to-Stan translation handles matrix-vector products and the vector dimension n, so the fix belongs in the translator, not the model code. Done means the generated Stan declares mu with the correct length and the model runs without error.

Written by the indexing model from the issue text.

Description

Hi, I am trying to construct a spline model using ulam(). Here is my R code:

library(rethinking)
library(splines)
data(cherry_blossoms)
d <- cherry_blossoms
d2 <- d[complete.cases(d$doy),]

B <- bs(d2$year,df=13,degree=3,intercept=TRUE)
m4.7 <- ulam(
    alist(
        D ~ dnorm(mu,sigma),
        mu <- a + B %*% w,
        a ~ dnorm(100,10),
        vector[n]:w ~ dnorm(0,10),
        sigma ~ dexp(1)
    ),
    data = list(D=d2$doy,B=B)
)

It can not run properly. I think it is because of the wrong translation to stan code, which is:

data{
     int n;
     vector[827] D;
     matrix[827,13] B;
}
parameters{
     real a;
     vector[n] w;
     real<lower=0> sigma;
}
model{
     vector[10751] mu;
    sigma ~ exponential( 1 );
    w ~ normal( 0 , 10 );
    a ~ normal( 100 , 10 );
    for ( i in 1:10751 ) {
        mu[i] = a + B[i] * w;
    }
    D ~ normal( mu , sigma );
}

ulam() can not identifies %*% correctly. mu should be an 827x1 vector, but in the stan code, it is considered as a 10751x1 vector.

I wonder how to fix this?

Thanks for your help.

Dominant language
R
Stars
2.4k
Forks
632
PR merge metrics
No merged PRs in 30d

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from rmcelreath/rethinking

All issues in rmcelreath/rethinking

Similar issues

More R issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.