R语言分类随机森林模型中分类变量ALEPlots绘制报错咨询
问题原因
这个是iml包的已知问题:当针对分类特征计算二分类模型的概率类ALE时,官方默认的plot方法内部存在类型处理逻辑错误,会将因子类型的特征水平误代入数值运算,因此抛出你遇到的non-numeric argument to binary operator报错。你的使用场景完全支持ALE plot生成,并非功能不支持。
连续变量ALE可以正常绘制是因为连续变量本身为数值型,不会触发该类型处理bug;PDP可正常运行是因为PDP的绘图逻辑和ALE不同,没有这部分错误。
解决方法
推荐直接提取ALE计算结果手动绘图,稳定性最高,修正后可运行代码如下:
library(randomForest) library(iml) library(ggplot2) # create sample data frame data <- data.frame(mortality = as.factor(c(rep("Low", 200), rep("High", 200))), veg = as.factor(rep(c("Shrub", "Oak", "conifer", "forb"), each = 50)), slope = rep(seq(0,90), length = 200)) # random forest model rfm <- randomForest(mortality ~., data = data) # 初始化预测器 low_predictor <- Predictor$new(rfm, data = data, type = "prob", class="Low") high_predictor <- Predictor$new(rfm, data = data, type = "prob", class="High") ## 分类变量veg的ALE计算 # 先计算ALE结果,不要直接套plot方法 low_veg_ale <- FeatureEffect$new(low_predictor, feature = "veg", method = "ale") high_veg_ale <- FeatureEffect$new(high_predictor, feature = "veg", method = "ale") # 提取结果数据框手动绘图(以Low类为例) low_veg_df <- low_veg_ale$results ggplot(low_veg_df, aes(x = veg, y = .value)) + geom_point(size = 3, color = "#2c3e50") + geom_errorbar(aes(ymin = .value - .sd, ymax = .value + .sd), width = 0.2, color = "#2c3e50") + labs(x = "植被类型", y = "ALE值(死亡率=Low的概率)") + theme_bw() ## 连续变量slope的ALE绘制逻辑不变,可直接用默认plot plot(FeatureEffect$new(low_predictor, feature = "slope", method = "ale"))
内容的提问来源于stack exchange,提问作者amp
相关产品推荐
相关产品推荐

