2015-11-11 56 views
2

我一些數據擬合到兩個高斯的混合物分佈在flexmix預測:從flexmix對象(R)

data("NPreg", package = "flexmix") 
mod <- flexmix(yn ~ x, data = NPreg, k = 2, 
      model = list(FLXMRglm(yn ~ x, family= "gaussian"), 
         FLXMRglm(yn ~ x, family = "gaussian"))) 

模型擬合如下:

> mod 

Call: 
flexmix(formula = yn ~ x, data = NPreg, k = 2, model = list(FLXMRglm(yn ~ x, family = "gaussian"), 
    FLXMRglm(yn ~ x, family = "gaussian"))) 

Cluster sizes: 
    1 2 
74 126 

convergence after 31 iterations 

但是,如何我實際上從這個模型預測?

當我做

pred <- predict(mod, NPreg) 

我得到的預測名單從兩個部件

爲了得到一個預測,我必須在簇大小像這樣加?

single <- (74/200)* pred$Comp.1[,1] + (126/200)*pred$Comp.2[,2] 

回答

4

我以下列方式使用flexmix進行預測:

pred = predict(mod, NPreg) 
clust = clusters(mod,NPreg) 
result = cbind(NPreg,data.frame(pred),data.frame(clust)) 
plot(result$yn,col = c("red","blue")[result$clust],pch = 16,ylab = "yn") 

Clusters in NPreg

而混淆矩陣:

table(result$class,result$clust) 

Confusion Matrix for NPreg

爲了獲得預測值yn,我選擇數據點所屬的集羣的組件值。

for(i in 1:nrow(result)){ 
    result$pred_model1[i] = result[,paste0("Comp.",result$clust[i],".1")][i] 
    result$pred_model2[i] = result[,paste0("Comp.",result$clust[i],".2")][i] 
} 

實際VS預測結果表明,該配合(這裏只增加其中一個作爲您的兩種機型都是一樣的,你可以使用pred_model2第二模型)。

qplot(result$yn, result$pred_model1,xlab="Actual",ylab="Predicted") + geom_abline() 

Actual Vs Predicted

RMSE = sqrt(mean((result$yn-result$pred_model1)^2)) 

給出了一個根均的5.54方誤差。

這個答案是基於許多SO答案,我通過flexmix工作時閱讀。它適用於我的問題。

您可能也對可視化兩個分佈感興趣。我的模型如下,它顯示了一些重疊,因爲組件的比例並不接近1

Call: 
flexmix(formula = yn ~ x, data = NPreg, k = 2, 
model = list(FLXMRglm(yn ~ x, family = "gaussian"), 
      FLXMRglm(yn ~ x, family = "gaussian"))) 

     prior size post>0 ratio 
Comp.1 0.481 102 129 0.791 
Comp.2 0.519 98 171 0.573 

'log Lik.' -1312.127 (df=13) 
AIC: 2650.255 BIC: 2693.133 

我還生成一個密度分佈與直方圖visulaize這兩個組件。這受到來自betareg維護者的SO answer的啓發。

a = subset(result, clust == 1) 
b = subset(result, clust == 2) 
hist(a$yn, col = hcl(0, 50, 80), main = "",xlab = "", freq = FALSE, ylim = c(0,0.06)) 
hist(b$yn, col = hcl(240, 50, 80), add = TRUE,main = "", xlab = "", freq = FALSE, ylim = c(0,0.06)) 
ys = seq(0, 50, by = 0.1) 
lines(ys, dnorm(ys, mean = mean(a$yn), sd = sd(a$yn)), col = hcl(0, 80, 50), lwd = 2) 
lines(ys, dnorm(ys, mean = mean(b$yn), sd = sd(b$yn)), col = hcl(240, 80, 50), lwd = 2) 

Density of Components

# Joint Histogram 
p <- prior(mod) 
hist(result$yn, freq = FALSE,main = "", xlab = "",ylim = c(0,0.06)) 
lines(ys, p[1] * dnorm(ys, mean = mean(a$yn), sd = sd(a$yn)) + 
     p[2] * dnorm(ys, mean = mean(b$yn), sd = sd(b$yn))) 

enter image description here

0

你可以傳遞一個額外的參數,以您的通話預測。

pred <- predict(mod, NPreg, aggregate = TRUE)[[1]][,1]