简体   繁体   English

我的 Gibbs 采样器中混合 model 的 NA 错误

[英]An NA error in my Gibbs sampler for mixture model

I am working on a Gibbs sampler and my code is as follows.我正在研究 Gibbs 采样器,我的代码如下。 The idea is (1)sample pi first (2) sample delta (3) sample beta .这个想法是 (1)sample pi first (2) sample delta (3) sample beta

  library(foreign)
   cognitive `=read.dta("http://www.stat.columbia.edu/~gelman/arm/examples/child.iq/kidiq.dta")`
 summary(cognitive)
 cognitive$mom_work = as.numeric(cognitive$mom_work > 1)
 cognitive$mom_hs = as.numeric(cognitive$mom_hs > 0)

# Modify column names of the data set
colnames(cognitive) = c("kid_score", "hs", "IQ", "work", "age")

 x<-cbind(cognitive$hs, cognitive$IQ, cognitive$work, cognitive$age)
 y<-cognitive$kid_score
 lmmodel<-lm(y~x-1, data=cognitive)
  NSim=3000 #iteration 
 Betahat=solve(t(x)%*%x)%*%t(x)%*%y

Error in if (delta[ite, j] == 1) rnorm(1, mu1, sigma1) else rnorm(1, mu0, : missing value where TRUE/FALSE needed In addition: Warning messages: 1: In rbinom(1, 1, prob = (p1/(p0 + p1))): NAs produced 2: In rbinom(1, 1, prob = (p1/(p0 + p1))): NAs produced if (delta[ite, j] == 1) rnorm(1, mu1, sigma1) else rnorm(1, mu0, : 需要 TRUE/FALSE 的缺失值另外:警告消息:1:在 rbinom(1, 1, prob = (p1/(p0 + p1))): 产生的 NA 2: In rbinom(1, 1, prob = (p1/(p0 + p1))): 产生的 NA

error is caused by the line prob=(pi[ite]*exp(-beta[ite-1,j]^2/(2*10^2)))/(((1-pi[ite])*10^3)*exp(-beta[ite-1,j]^2/(2*10^(-4)))+pi[ite-1]*exp(-beta[ite-1,j]^2/(2*10^2))) : at some iteration prob becomes greater than 1, so rbern() returns NA .错误是由行prob=(pi[ite]*exp(-beta[ite-1,j]^2/(2*10^2)))/(((1-pi[ite])*10^3)*exp(-beta[ite-1,j]^2/(2*10^(-4)))+pi[ite-1]*exp(-beta[ite-1,j]^2/(2*10^2))) :在某些迭代中prob变得大于 1,因此rbern()返回NA Check your formula.检查你的公式。

UPD. UPD。 For debugging, add the following before your delta[ite,j]=rbern(... line:对于调试,请在delta[ite,j]=rbern(...行之前添加以下内容:

prob_full <- (pi[ite]*exp(-beta[ite-1,j]^2/(2*10^2)))/(((1-pi[ite])*10^3)*exp(-beta[ite-1,j]^2/(2*10^(-4)))+pi[ite-1]*exp(-beta[ite-1,j]^2/(2*10^2)));
cat('\n',ite,j,prob_full)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM