分類建模

R 的自然語言處理入門

Kasey Jones

Research Data Scientist

步驟重點回顧

  1. 清理/準備資料

    • 僅篩選 Boxer/Napoleon 句子
    • 建立清理後的文字標記
    • 以 TFIDF 權重建立文件-詞矩陣
  2. 建立訓練集與測試集

  3. 在訓練集上訓練模型
  4. 在測試集回報準確率
R 的自然語言處理入門

步驟 2:切分資料

set.seed(1111)
sample_size <- floor(0.80 * nrow(animal_matrix))
train_ind <- sample(nrow(animal_matrix), size = sample_size)
train <- animal_matrix[train_ind, ]
test <- animal_matrix[-train_ind, ]
R 的自然語言處理入門

隨機森林模型

R 的自然語言處理入門

分類範例

library(randomForest)
rfc <- randomForest(x = as.data.frame(as.matrix(train)), 
                    y = animal_sentences$Name[train_ind], nTree = 50)
rfc
Call:
 randomForest(...
        OOB estimate of  error rate: 23.33%
Confusion matrix:
         boxer napoleon class.error
boxer       37       20   0.3508772
napoleon     8       55   0.1269841
R 的自然語言處理入門

混淆矩陣

Call:
 randomForest(...
        OOB estimate of  error rate: 23.33%
Confusion matrix:
         boxer napoleon class.error
boxer       37       20   0.3508772
napoleon     8       55   0.1269841

準確率:(37 + 55) / (37 + 20 + 8 + 55) = 76%

R 的自然語言處理入門

測試集預測

y_pred <- predict(rfc, newdata = as.data.frame(as.matrix(test)))
table(animal_sentences[-train_ind, ]$Name, y_pred)
          y_pred
           boxer napoleon
  boxer       14        4
  napoleon     2       10
  • boxer 的準確率:14/18
  • napoleon 的準確率:10/12
  • 整體準確率:24/30 = 80%
R 的自然語言處理入門

分類練習

R 的自然語言處理入門

Preparing Video For Download...