连续型结果

R 中的树模型机器学习

Sandro Raabe

Data Scientist

数据集

head(chocolate, 5)
final_grade review_date   cocoa_percent  company_location  bean_type              broad_bean_origin
<dbl>       <int>         <dbl>          <fct>             <fct>                  <fct>
3           2009          0.8            U.K.              "Criollo, Trinitario"  "Madagascar"
3.75        2012          0.7            Guatemala         "Trinitario"           "Madagascar"
2.75        2009          0.75           Colombia          "Forastero (Nacional)" "Colombia"
3.5         2014          0.74           Zealand           ""                     "Papua New Guinea"
3.75        2011          0.72           Australia         ""                     "Bolivia"
R 中的树模型机器学习

构建回归树

spec <- decision_tree() %>%

set_mode("regression") %>%
set_engine("rpart")
print(spec)
Decision Tree Model Specification
(regression)

Computational engine: rpart
model <- spec %>%
  fit(formula = final_grade ~ .,

data = chocolate_train)
print(model)
parsnip model object

Fit time:  20ms 
n= 1437 

node), split, n, deviance, yval
      * denotes terminal node
R 中的树模型机器学习

使用回归树进行预测

# 在新数据上做预测
predict(model, new_data = chocolate_test)
.pred
<dbl>
3.281915
3.435234
3.281915
3.833931
3.281915
3.514151
3.273864
3.514151
R 中的树模型机器学习

分而治之

分而治之

R 中的树模型机器学习

超参数

回归树目标:
  • 组内方差或均值偏差低
设计参数:
  • min_n:节点继续分裂所需最少样本数(默认:20)
  • tree_depth:树的最大深度(默认:30)
  • cost_complexity:复杂度惩罚(默认:0.01)
在最初步骤设置:
decision_tree(tree_depth = 4, cost_complexity = 0.05) %>% 
    set_mode("regression")
R 中的树模型机器学习

理解模型输出

decision_tree(tree_depth = 1) %>%
  set_mode("regression") %>%              
  set_engine("rpart")  %>%
  fit(formula = final_grade ~ .,
      data = chocolate_train)
parsnip model object

Fit time:  1ms
n= 1000

node), split, n, yval

1) root                 1000  2.347450
2) cocoa_percent>=0.905   16  2.171875 *
3) cocoa_percent<0.905   984  3.190803 *
  • 使用 tree_depth = 1 的模型

 

 

  • 可视化:

决策树

R 中的树模型机器学习

开始做回归!

R 中的树模型机器学习

Preparing Video For Download...