預測與評估

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:預測為 yes,真值為 yes
  • TN:預測為 no,真值為 no
  • FP:預測為 yes,真值為 no
  • FN:預測為 no,真值為 yes

混淆矩陣_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{n of correct predictions}}{\text{n of total predictions}}$$

  • 函式名稱: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...