分类建模

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...