Multiply two 1*k vectors but got No matches for: real ~ normal(matrix, real) error in pystan

泪湿孤枕 提交于 2019-12-24 20:36:05

问题


Now I am implementing the pmf model as below:

pmf_code = """

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(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);
}
}
generated_quantities{
for (d in 1:D_new){
   r_new[d] <- normal(u[jj_new[d]]' * i[ii_new[d]], 1/alpha);
}
}
"""     

but got an No matches for: real ~ normal(matrix, real) error in this line of code:

for (d in 1:D){
   r[d] ~ normal(u[jj[d]]' * i[ii[d]], 1/alpha);
}

But the jj[d] should be a int, denoting the id of user. And u[int] should be a row_vector has k factors and so is i[ii[d]]. The product of them should be a single real value, why stan said it was a matrix?

Thanks in advance!

EDIT:

The initial problem has been solved by adding a sum of the product. But now another error occurs:

No matches for: 

row vector ~ normal(int, matrix) 

for (n in 1: N){
   u[n] ~ normal(0,(1/alpha_u) * I);
}

In the pmf model, I is 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. Thanks.


回答1:


Stan is a statically typed language. A vector multiplied by a row_vector will result in a matrix. In this case, it's a 1x1 matrix. For the return type of operator*, see page 355 of the v2.9.0 version of the manual.

Rather than multiplying, use dot_product() instead.



来源:https://stackoverflow.com/questions/35296429/multiply-two-1k-vectors-but-got-no-matches-for-real-normalmatrix-real-err

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!