You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于波士顿房价数据集,如何构建使用最优树数量的树模型?

如何在tree包中应用交叉验证得到的最优树数量?

问题背景

使用波士顿房价数据集(Boston Housing)构建回归树模型时,通过cv.tree()交叉验证得到了最优树节点数量(示例为8棵),但遇到以下问题:

  • 在tree::tree()函数中添加trees参数会触发报错:Error in tree.control(nobs, ...) : unused argument (trees = 1)
  • 在predict()函数中添加size参数无效果,计算出的RMSE始终不变

解决方案

tree包的逻辑是先训练一棵完整的回归树,再通过交叉验证确定最优剪枝后的节点数,而非直接指定训练时的树数量。正确的流程是:

  1. 训练完整的回归树模型
  2. 用cv.tree()获取最优节点数n.trees
  3. 使用prune.tree()对完整树进行剪枝,保留最优节点数
  4. 用剪枝后的模型进行预测并评估

修正后的完整代码示例

library(tree)
library(MASS)

tree.test.RMSE <- 0
df <- MASS::Boston

for (i in 1:5){
  # 划分训练、测试、验证集
  idx <- sample(seq(1, 3), size = nrow(df), replace = TRUE, prob = c(.6, .2, .2))
  train <- df[idx == 1,]
  test <- df[idx == 2,]
  validation <- df[idx == 3,]
  
  # 1. 训练完整回归树
  tree.model <- tree::tree(medv ~ . , data = train)
  
  # 2. 交叉验证找最优节点数
  tree.model.cv <- cv.tree(tree.model)
  n.trees <- tree.model.cv$size[which.min(tree.model.cv$dev)]
  
  # 3. 根据最优节点数剪枝
  pruned_tree <- prune.tree(tree.model, best = n.trees)
  
  # 4. 用剪枝后的模型预测测试集并计算RMSE
  test_pred <- predict(pruned_tree, newdata = test)
  rmse <- sqrt(mean((test$medv - test_pred)^2))
  tree.test.RMSE <- tree.test.RMSE + rmse
}

# 输出5折交叉验证的平均RMSE
cat("平均测试RMSE:", tree.test.RMSE/5, "\n")

关键说明

  • prune.tree()的best参数用于指定剪枝后保留的节点数量,对应cv.tree()得到的最优size值
  • 无需在tree()或predict()中额外添加trees/size参数,剪枝后的模型已经是最优结构

内容的提问来源于stack exchange,提问作者Russ Conte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 03:10:13