在R中用训练数据集构建决策树后无法正常绘图的解决方案咨询
问题描述
尝试使用如下训练数据集在R中创建决策树:
structure(list(Color = c(0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0), Size = c(1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0), Act = c(1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0), Age = c(1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0), Inflated = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,2L, 2L, 2L), levels = c("F", "T"), class = "factor")), class = "data.frame", row.names = c(NA, -22L))
执行以下代码后:
Training1 <- as.data.frame(unclass(Training1), stringsAsFactors = TRUE) tree1<- ctree(Inflated ~ ., Training1)
调用plot(tree1)无法生成正常的决策树图形,出现布局异常。
解决建议
- 调整绘图参数:
ctree默认绘图可能因窗口尺寸或布局设置导致显示异常,尝试指定简化布局或调整图形尺寸:# 使用simple类型简化树结构显示 plot(tree1, type = "simple") # 若在脚本中运行,可指定输出图形尺寸避免压缩 png("decision_tree.png", width = 1000, height = 800) plot(tree1, type = "simple") dev.off() - 转换变量类型:你的输入特征(Color、Size、Act、Age)为数值型,但实际是二分类变量,转为因子类型后
ctree的划分逻辑和绘图会更合理:# 将数值型分类变量转为因子 Training1[, c("Color", "Size", "Act", "Age")] <- lapply(Training1[, c("Color", "Size", "Act", "Age")], as.factor) # 重新训练决策树 tree1 <- ctree(Inflated ~ ., Training1) # 绘图 plot(tree1) - 使用替代绘图工具:如果
party包的plot.ctree仍有问题,可切换到rpart包实现决策树,其绘图更稳定直观:library(rpart) library(rpart.plot) # 训练rpart决策树 rpart_tree <- rpart(Inflated ~ ., data = Training1) # 生成清晰的决策树可视化 rpart.plot(rpart_tree, box.palette = "GnBu", shadow.col = "gray", nn = TRUE)
内容的提问来源于stack exchange,提问作者ano273
相关产品推荐
相关产品推荐

