2017-02-03 66 views
1

我現在正在學習斯坦,想要實現一個簡單的混合模型。斯坦的混合模型 - 矢量化

在參考手冊(斯坦參考-2.14.0)已經有一個解決方案:

data { 
    int<lower=1> K; // number of mixture components 
    int<lower=1> N; // number of data points 
    real y[N]; // observations 
} 
parameters { 
    simplex[K] theta; // mixing proportions 
    real mu[K]; // locations of mixture components 
    real<lower=0> sigma[K]; // scales of mixture components 
} 
model { 
    real ps[K]; // temp for log component densities 
    sigma ~ cauchy(0, 2.5); 
    mu ~ normal(0, 10); 
    for (n in 1:N) { 
    for (k in 1:K) { 
     ps[k] = log(theta[k]) 
     + normal_lpdf(y[n] | mu[k], sigma[k]); 
    } 
    target += log_sum_exp(ps); 
    } 
} 

下一個頁描述了外環的向量化是不可能的。但是,我想知道內部循環的parallization仍然是。

所以我嘗試了以下型號:

data { 
    int<lower=1> K; // number of mixture components 
    int<lower=1> N; // number of data points 
    real y[N]; // observations 
} 

parameters { 
    simplex[K] theta; // mixing proportions 
    vector[K] mu; // locations of mixture components 
    vector<lower=0>[K] sigma; // scales of mixture components 
} 

model { 
    vector[K] ps;//[K]; // temp for log component densities 
    vector[K] ppt; 
    sigma ~ cauchy(0, 2.5); 
    mu ~ normal(0, 10); 
    for (n in 1:N) { 
    ppt = log(theta); 
    /* 
    for (k in 1:K) { 
     ps[k] = ppt[k] + //log(theta[k]) 
     normal_lpdf(y[n] | mu[k], sigma[k]); 
    } 
    */ 
    ps = ppt + normal_lpdf(y[n] | mu, sigma); 
    target += log_sum_exp(ps); 
    } 
} 

......而這種模式作出錯誤的估計(相對於原始模型)。

data("faithful") 
erupdata <- list(
    K = 2, 
    N = length(faithful$eruptions), 
    y = faithful$eruptions 
) 

fiteruptions <- stan(file = 'mixturemodel.stan', data = erupdata, iter = 1000, chains = 1) 

我想知道,我對模型規範的理解錯誤。我想了解語法提供的差異(其中包括vector[K]real[K]之間的區別),也許可以深入瞭解斯坦。

回答

1

第二個程序定義了不同的密度。 normal_lpdf返回單個標量值,該值是數據/參數容器上日誌pdf的總和。

手冊中有關於矩陣/向量與數組的章節。

你想拉高效率的ppt的定義。