构建 BoW 朴素贝叶斯分类器

Python 中的 NLP 特征工程

Rounak Banik

Data Scientist

垃圾短信过滤

message label
WINNER!! As a valued network customer you have been selected to receive a $900 prize reward! To claim call 09061701461 spam
Ah, work. I vaguely remember that. What does it feel like? ham
Python 中的 NLP 特征工程

步骤

  1. 文本预处理
  2. 构建词袋模型(表示)
  3. 机器学习
Python 中的 NLP 特征工程

使用 CountVectorizer 进行文本预处理

CountVectorizer 参数

  • lowercase: False, True
  • strip_accents: 'unciode', 'ascii', None
  • stop_words: 'english', list, None
  • token_pattern: regex
  • tokenizer: function
Python 中的 NLP 特征工程

构建 BoW 模型

# 导入 CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer

# 创建 CountVectorizer 对象 vectorizer = CountVectorizer(strip_accents='ascii', stop_words='english', lowercase=False)
# 导入 train_test_split from sklearn.model_selection import train_test_split # 划分训练集与测试集 X_train, X_test, y_train, y_test = train_test_split(df['message'], df['label'], test_size=0.25)
Python 中的 NLP 特征工程

构建 BoW 模型

...
...
# 生成训练集 BoW 向量
X_train_bow = vectorizer.fit_transform(X_train)

# 生成测试集 BoW 向量 X_test_bow = vectorizer.transform(X_test)
Python 中的 NLP 特征工程

训练朴素贝叶斯分类器

# 导入 MultinomialNB
from sklearn.naive_bayes import MultinomialNB

# 创建 MultinomialNB 对象 clf = MultinomialNB()
# 训练 clf clf.fit(X_train_bow, y_train)
# 计算测试集准确率 accuracy = clf.score(X_test_bow, y_test) print(accuracy)
0.760051
Python 中的 NLP 特征工程

Passons à la pratique !

Python 中的 NLP 特征工程

Preparing Video For Download...