我将一些数据拟合到flexmix
中的两个高斯的混合分布:
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]
答案 0 :(得分:6)
我以下列方式使用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")
混乱矩阵:
table(result$class,result$clust)
为了获得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()
RMSE = sqrt(mean((result$yn-result$pred_model1)^2))
给出5.54
的均方根误差。
这个答案基于我在使用flexmix
时阅读的许多SO答案。它对我的问题很有用。
您可能也有兴趣可视化这两个发行版。我的模型如下,显示了一些重叠,因为组件的比率不接近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
我还使用直方图生成密度分布,以对两个组件进行可视化。这是受到来自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)
# 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)))
答案 1 :(得分:0)
您可以将另一个参数传递给预测调用。
pred <- predict(mod, NPreg, aggregate = TRUE)[[1]][,1]