# NOT RUN {
## This is an example of Gibbs sampling on Gaussian mixture models, using Dirichlet Process.
## generate some Gaussian mixture samples for demo purpose
x <- rbind(
rGaussian(50,mu = c(-1.5,1.5),Sigma = matrix(c(0.1,0.03,0.03,0.1),2,2)),
rGaussian(60,mu = c(-1.5,-1.5),Sigma = matrix(c(0.8,0.5,0.5,0.8),2,2)),
rGaussian(70,mu = c(1.5,1.5),Sigma = matrix(c(0.3,0.05,0.05,0.3),2,2)),
rGaussian(50,mu = c(1.5,-1.5),Sigma = matrix(c(0.5,-0.08,-0.08,0.5),2,2))
)
## Step1: Initialize----------------------------------------------
maxit <- 100 #iterative for maxit times
burnin <- 50 #number of burnin samples
z <- matrix(1L,nrow(x),maxit-burnin) #labels
## create an "GaussianNIW" object to track all the changes.
obj <- DP(gamma = list(alpha=1,H0aF="GaussianNIW",parH0=list(m=c(0,0),k=0.001,v=2,S=diag(2))))
ss <- sufficientStatistics(obj,x=x,foreach = TRUE) #sufficient statistics of each x
N <- nrow(x)
for(i in 1L:N){ # initialize labels before Gibbs sampling
z[i,1] <- rPosteriorPredictive(obj = obj,n=1,x=x[i,,drop=FALSE])
posterior(obj = obj,ss = ss[[i]], z = z[i,1])
}
## Step2: Main Gibbs sampling loop--------------------------------
it <- 0 #iteration tracker
pb <- txtProgressBar(min = 0,max = maxit,style = 3)
while(TRUE){
if(it>burnin) colIdx <- it-burnin
else colIdx <- 1
for(i in 1L:N){
## remove the sample information from the posterior
posteriorDiscard(obj = obj,ss = ss[[i]],z=z[i,colIdx])
## get a new sample
z[i,colIdx] <- rPosteriorPredictive(obj = obj,n=1,x=x[i,,drop=FALSE])
## add the new sample information to the posterior
posterior(obj = obj,ss = ss[[i]],z=z[i,colIdx])
}
if(it>burnin & colIdx<ncol(z)) z[,colIdx+1] <- z[,colIdx] #copy result of previous iteration
it <- it+1
setTxtProgressBar(pb,it)
if(it>=maxit){cat("\n");break}
plot(x=x[,1],y=x[,2],col=z[,colIdx]) #to see how the labels change
}
## Step3: Estimate group labels of each observation---------------
col <- apply(z,1,function(l){
tmp <- table(l)
## pick the most frequent group label in the samples to be the best estimate
names(tmp)[which.max(tmp)]
})
plot(x=x[,1],y=x[,2],col=col)
# }
Run the code above in your browser using DataLab