# NOT RUN {
# }
# NOT RUN {
require(mixAK)
data(Acidity)
y <- Acidity
w <- c(0.50, 0.17, 0.33)
mu <- c(4, 5, 6)
sigma2 <- c(0.08, 0.10, 0.14)
Z <- do.call(cbind, lapply(1:3, function(i)
w[i]*dnorm(y, mu[i], sqrt(sigma2[i]))))
Z <- apply(Z, 1, function(x) which(x==max(x))[1])
result <- uvnm.rjmcmc(y, nsweep=200000, kmax=30, k=3,
w, mu, sigma2, Z)
ksave <- result$k.save
round(table(ksave[-(1:100000)])/100000,4)
#conditional density estimation
focus.k <- 3
pick.k <- which(ksave==focus.k)
w <- unlist(result$w.save[pick.k])
mu <- unlist(result$mu.save[pick.k])
sigma2 <- unlist(result$sigma2.save[pick.k])
den.estimate <- rep(w, each=length(y)) *
dnorm(rep(y, length(w)), mean=rep(mu, each=length(y)),
sd=rep(sqrt(sigma2), each=length(y)))
den.estimate <- rowMeans(matrix(den.estimate, nrow=length(y)))*focus.k
#within-sample classification
class <- apply(result$Z.save[,pick.k], 1,
function(x) c(sum(x==1), sum(x==2), sum(x==3)))
class <- max.col(t(class))
#visualize the results
hist(y, freq=FALSE, breaks=20, axes=FALSE, ylim=c(-0.3, 1),
main="Density Estimation and Classification", ylab="")
axis(2, at=c(-(3:1)/10, seq(0,10,2)/10), labels=c(3:1, seq(0,10,2)/10),
font=2)
lines(sort(y), den.estimate[order(y)], col="red")
for(i in 1:3){
points(y[class==i], rep(-i/10, length(y[class==i])), col=i, pch=i)
}
mtext("Density", 2, at=0.5, line=2)
mtext("Classification", 2, at=-0.15, line=2)
# }
Run the code above in your browser using DataLab