预测与评估

R 中的树模型机器学习

Sandro Raabe

Data Scientist

在新数据上预测

通用调用:
predict(model, new_data, type)
参数:
  1. 训练好的模型
  2. 需要预测的数据集
  3. 预测类型:类别或概率
R 中的树模型机器学习

在新数据上预测

predict(model, new_data = test_data, 
               type = "class")
  .pred_class
  <fct>      
1 no         
2 no         
3 yes        
4 no
predict(model, new_data = test_data, 
               type = "prob")
     .pred_no  .pred_yes
     <dbl>     <dbl>
1    0.866     0.134
2    0.956     0.044
3    0.672     0.328
4    0.877     0.123
R 中的树模型机器学习

混淆矩阵

混淆矩阵_1

  • 揭示模型的混淆程度
R 中的树模型机器学习

混淆矩阵

混淆矩阵_2

R 中的树模型机器学习

混淆矩阵

混淆矩阵_3

R 中的树模型机器学习

混淆矩阵

混淆矩阵_4

  • 对角线:预测正确
  • 非对角线:预测错误
R 中的树模型机器学习

混淆矩阵

 

  • TP:预测为,真实为
  • TN:预测为,真实为
  • FP:预测为,真实为
  • FN:预测为,真实为

混淆矩阵_4

R 中的树模型机器学习

创建混淆矩阵

# Combine predictions and truth values
pred_combined <- predictions %>% 
   mutate(true_class = test_data$outcome)

pred_combined
  .pred_class  true_class
  <fct>        <fct>     
1 no           no        
2 no           yes       
3 no           no        
4 yes          yes
# Calculate the confusion matrix
conf_mat(data = pred_combined,

estimate = .pred_class,
truth = true_class)
             Truth
Prediction    no   yes
        no   116    31
       yes    12    40
R 中的树模型机器学习

准确率

  $$\text{accuracy} = \frac{\text{正确预测数}}{\text{总预测数}}$$

  • 函数名:accuracy()
  • conf_mat() 相同参数
    • dataestimatetruth
    • yardstick 中的通用结构
accuracy(pred_combined,
         estimate = .pred_class,
         truth = true_class)
  .metric     .estimate
  <chr>           <dbl>
1 accuracy        0.708
R 中的树模型机器学习

让我们来评估!

R 中的树模型机器学习

Preparing Video For Download...