Reputation: 1490
I am a newbie to both stan and machine learning. Now I'd like to implement the pmf model. Here is part of my code:
pmf_cod="""
data {
int<lower=0> K; //number of factors
int<lower=0> N; //number of user
int<lower=0> M; //number of item
int<lower=0> D; //number of observation
int<lower=0> D_new; //number of pridictor
int<lower=0, upper=N> ii[D]; //item
int<lower=0, upper=M> jj[D]; //user
int<lower=0, upper=N> ii_new[D_new]; // item
int<lower=0, upper=N> jj_new[D_new]; // user
real<lower=0, upper=5> r[D]; //rating
real<lower=0, upper=5> r_new[D_new]; //pridict rating
}
parameters {
row_vector[K] i[M]; // item profile
row_vector[K] u[N]; // user profile
real<lower=0> alpha;
real<lower=0> alpha_i;
real<lower=0> alpha_u;
}
transformed parameters {
matrix[N,M] I; // indicator variable
I <- rep_matrix(0, N, M);
for (d in 1:D){
I[ii[d]][jj[d]] <- 1;
}
}
model {
for (d in 1:D){
r[d] ~ normal(sum(u[jj[d]]' * i[ii[d]]), 1/alpha);
}
for (n in 1: N){
u[n] ~ normal(0,(1/alpha_u) * I);
}
for (m in 1:M){
i[m] ~ normal(0,(1/alpha_i) * I);
}
}
"""
But I got a error:No matches for: row vector ~ normal(int, matrix)
in this line of code:
for (n in 1: N){
u[n] ~ normal(0,(1/alpha_u) * I);
}
Where I
is a unit matrix. So the product of (1/alpha_u) * I
is also a matrix. But stan just accept vector or real value as variance. I wonder how to transform it to a vector or a single value.
Thank you in advance!
Upvotes: 0
Views: 93
Reputation: 4980
It appears as if you intend to be using the multivariate normal density, in which case the function you are looking for is multi_normal
rather than normal
. However, the multi_normal
function needs a mean vector as its first argument, so you would need to call it as
u[n] ~ multi_normal(rep_vector(0, K), (1/alpha_u) * I);
In addition, there is no need to create I
in the transformed parameters
block when it should be created in the transformed data
block.
All that said, you should never use the multi_normal
density in Stan when the variance-covariance matrix is diagonal. Under this assumption, the multivariate normal distribution factors into a product of univariate normal distributions, so you would be better off doing
u[n] ~ normal(0, 1 / alpha_u);
Upvotes: 1