问题描述
在我的一项稳健性测试中,我想对部分依赖图进行交叉验证,但我不知道从哪里开始。我的模型是回归树,我有基于整个数据集的部分依赖图。我的问题是:
-
如果我将数据集随机分成 10 个随机样本,并根据每个随机样本计算变量 X 对 Y 的部分依赖性,我如何平均 10 个样本的结果以得出一个图?我在 python 或 R 中找不到任何内置函数来做到这一点?
-
与上面相同的任务,但是,我想绘制2-way交互的部分依赖图,例如,Y上的变量X1和X2?
谢谢。
解决方法
对于我在评论中的回答,如果您想查看冰曲线的变化,您可以像这样引导它们:
library(pdp)
library(randomForest)
library(ICEbox)
data(boston)
X <- as.data.frame(model.matrix(cmedv ~ .,data=boston)[,-1])
y <- model.response(model.frame(cmedv ~ .,data=boston))
boston.rf <- randomForest(x=X,y=y)
bice <- ice(boston.rf,X=X,predictor = "lstat")
res <- NULL
for(i in 1:1000){
inds <- sample(1:nrow(bice$ice_curves),nrow(bice$ice_curves),replace=TRUE)
res <- rbind(res,colMeans(bice$ice_curve[inds,]))
}
out <- data.frame(
fit = colMeans(bice$ice_curves),lwr = apply(res,2,quantile,.025),upr = apply(res,.975),x=bice$gridpts
)
library(ggplot2)
ggplot(out,aes(x=x,y=fit,ymin=lwr,ymax=upr)) +
geom_ribbon(alpha=.25) +
geom_line() +
theme_bw() +
labs(x="lstat",y="Prediction")
或者,您可以查看每个评估点的冰图的不同分位数。
tmp <- t(apply(bice$ice_curves,c(0,.025,.05,.1,.25,.5,.75,.9,.95,.975,1)))
head(tmp)
tmp <- as.data.frame(tmp)
names(tmp) <- c("l1","l2","l3","l4","l5","med","u1","u2","u3","u4","u5")
tmp$x <- bice$gridpts
ggplot(tmp,y=med)) +
geom_ribbon(aes(ymin=l1,ymax=u1),alpha=.2) +
geom_ribbon(aes(ymin=l2,ymax=u2),alpha=.2) +
geom_ribbon(aes(ymin=l3,ymax=u3),alpha=.2) +
geom_ribbon(aes(ymin=l4,ymax=u4),alpha=.2) +
geom_ribbon(aes(ymin=l5,ymax=u5),alpha=.2) +
geom_line() +
theme_bw() +
labs(x="lstat",y="Prediction")