在决策树CART中使用回归
1 简介
决策树也可以用作回归任务,我们叫作回归树。而回归树的结构还是树形结构,但是属性选择与生长方式和分类的决策树有不同。
要讲回归树一定会提到CART树,CART树全称Classification And Regression Trees,包括分类树与回归树。
CART的特点是:假设决策树是二叉树,内部结点特征的取值为「是」和「否」,右分支是取值为「是」的分支,左分支是取值为「否」的分支。
这样的决策树等价于「递归地二分每个特征」,将输入空间(特征空间)划分为有限个单元,并在这些单元上确定预测的概率分布,也就是在输入给定的条件下输出的条件概率分布。
2 回归树示例
func regressionExample() {
fmt.Println("\nRegression Tree Example:")
// 训练数据:简单的正弦函数近似
features := make([][]float64, 0)
labels := make([]float64, 0)
for x := 0.0; x < 10.0; x += 0.5 {
features = append(features, []float64{x})
labels = append(labels, math.Sin(x))
}
// 创建并训练回归树
tree := NewCART(5, 3, true)
tree.Fit(features, labels)
// 打印树结构
fmt.Println("Tree structure (simplified):")
tree.PrintTree()
// 测试数据
testFeatures := [][]float64{
{1.2},
{3.4},
{5.6},
{7.8},
}
// 预测
predictions := tree.PredictBatch(testFeatures)
// 输出结果
for i, pred := range predictions {
trueValue := math.Sin(testFeatures[i][0])
fmt.Printf("x = %.1f: predicted = %.4f, true = %.4f, error = %.4f\n",
testFeatures[i][0], pred, trueValue, math.Abs(pred-trueValue))
}
}
2.3 主函数
func main() {
classificationExample()
regressionExample()
}
3. 测试输出示例
运行上述代码后,你会看到类似以下的输出:
Classification Tree Example:
Tree structure:
Feature[0] <= 1.50
Leaf: class 1
Feature[1] <= 1.50
Leaf: class 1
Leaf: class 0
Sample [1.5 1.5]: predicted class = 1
Sample [2.5 1]: predicted class = 0
Sample [1 1.5]: predicted class = 1
Regression Tree Example:
Tree structure (simplified):
Feature[0] <= 4.75
Feature[0] <= 2.25
Feature[0] <= 1.25
Leaf: 0.8415
Leaf: 0.9482
Feature[0] <= 3.75
Feature[0] <= 3.25
Leaf: -0.7568
Leaf: -0.9589
Leaf: -0.7055
Feature[0] <= 7.25
Feature[0] <= 5.75
Leaf: -0.9051
Leaf: -0.9395
Feature[0] <= 8.75
Leaf: 0.4546
Leaf: 0.8342
x = 1.2: predicted = 0.8415, true = 0.9320, error = 0.0905
x = 3.4: predicted = -0.7568, true = -0.2555, error = 0.5013
x = 5.6: predicted = -0.9051, true = -0.6313, error = 0.2738
x = 7.8: predicted = 0.4546, true = 1.0000, error = 0.5454
4. 实现说明
CART算法特点:
支持分类和回归任务
分类使用基尼不纯度作为分裂标准
回归使用方差作为分裂标准
支持最大深度和最小样本数等预剪枝参数
主要功能:
Fit(): 训练决策树
Predict(): 预测单个样本
PredictBatch(): 批量预测
PrintTree(): 打印树结构(用于调试)
5 小结
分类和回归的总结
回归树使用 树来表示 递归分区,终端节点 表示分区的 单元格和 每个 分区的附加模型。 递归调用树 用于 无监督机器学习 算法中的分类和回归。
最近邻被广泛使用——超级能力:可以迅速学习新类别,并从一个或多个例子中进行预测•
朴素贝叶斯作为密度估计的一部分,代表了一种常见的假设,通常更典型地作为一种方法,而不是最终的预测器——超级能力:从大量数据中快速估计;从有限数据中并非糟糕的估计•
逻辑回归被广泛使用——超级能力:有效地从高维特征中进行预测;
良好的置信度估计• 线性回归被广泛使用——超级能力:
可以外推、解释关系,并从多个变量中预测连续值• 几乎所有算法都涉及最近邻、逻辑回归或线性回归.
- 点赞
- 收藏
- 关注作者
评论(0)