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

R语言tree函数如何判断构建分类树或回归树?

How does the tree() function determine whether to build a classification or regression tree?

Great question! You’re exactly right — the tree() function from the tree package automatically decides between a classification tree and regression tree based on the type of your target variable. Let’s break this down with your examples:

1. Classification Tree: When the target is a factor

In your first code snippet:

library(tree)
library(ISLR)
library(dplyr)
Carseats <- Carseats %>% mutate(High = factor(ifelse(Sales <= 8, "No", "Yes")))
tree.carseats <- tree(High~ . -Sales, Carseats)

The target variable High is a factor (it has two categorical levels: "Yes" and "No"). The tree() function detects this categorical type and builds a classification tree, using criteria like Gini impurity or cross-entropy to split nodes. The goal here is to minimize misclassification error across the resulting subgroups.

2. Regression Tree: When the target is numeric

In your second example:

library(MASS)
set.seed(1)
tree.boston=tree(medv~ .,Boston)

Here, the target medv (median home value) is a numeric continuous variable. The function switches to regression tree mode, using sum of squared errors (SSE) to split nodes. The objective now is to reduce the variance of the target within each split subgroup.

Quick verification tip

You can confirm the type of tree you’ve built by running summary() on your tree object. For a classification tree, it’ll explicitly state "classification tree" and list class counts for each terminal node; for a regression tree, it’ll note "regression tree" and report deviance related to squared errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:42:39