R语言tree函数如何判断构建分类树或回归树?
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

