朴素贝叶斯情感分类原理
核心思想:基于贝叶斯定理,计算文本属于某类别的概率,选择概率最大的类别作为预测结果。
关键公式:
P(类别∣文本)∝P(类别)×∏i=1nP(单词i∣类别)P(类别∣文本)∝P(类别)×i=1∏nP(单词i∣类别)
实现步骤:
- 数据预处理:清洗文本、分词、去除停用词
- 特征提取:将文本转换为词频向量(TF-IDF/BOW)
- 模型训练:计算先验概率和条件概率
- 分类预测:对新文本计算各类别概率
完整代码实现
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import string
import nltk
# 下载NLTK资源(首次运行需要执行)
nltk.download('punkt')
nltk.download('stopwords')
# 1. 数据准备(示例数据)
data = {
'text': [
'I love this movie, it is amazing!',
'Terrible acting and boring plot.',
'Great cinematography but weak story.',
'Absolutely fantastic experience!',
'Waste of time, would not recommend.',
'The best film of the year!',
'Poor character development.',
'Loved every minute of it!'
],
'sentiment': ['positive', 'negative', 'negative', 'positive',
'negative', 'positive', 'negative', 'positive']
}
df = pd.DataFrame(data)
# 2. 文本预处理
def preprocess_text(text):
# 转小写
text = text.lower()
# 去除标点
text = text.translate(str.maketrans('', '', string.punctuation))
# 分词
tokens = word_tokenize(text)
# 去除停用词
stop_words = set(stopwords.words('english'))
tokens = [word for word in tokens if word not in stop_words]
return ' '.join(tokens)
df['cleaned_text'] = df['text'].apply(preprocess_text)
# 3. 特征提取(TF-IDF向量化)
tfidf = TfidfVectorizer(max_features=1000)
X = tfidf.fit_transform(df['cleaned_text'])
y = df['sentiment']
# 4. 划分训练/测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y)
# 5. 训练模型
model = MultinomialNB()
model.fit(X_train, y_train)
# 6. 模型评估
y_pred = model.predict(X_test)
print(f"准确率: {accuracy_score(y_test, y_pred):.2f}")
print("混淆矩阵:")
print(confusion_matrix(y_test, y_pred))
# 7. 新文本预测
def predict_sentiment(text):
cleaned_text = preprocess_text(text)
vector = tfidf.transform([cleaned_text])
proba = model.predict_proba(vector)[0]
prediction = model.predict(vector)[0]
return {
'text': text,
'prediction': prediction,
'positive_prob': proba[1],
'negative_prob': proba[0]
}
# 测试预测
test_text = "This movie was surprisingly good!"
result = predict_sentiment(test_text)
print(f"\n预测结果: {result}")
代码解析
-
数据预处理:
- 转换为小写
- 移除标点符号
- 使用NLTK分词
- 过滤英语停用词
-
特征工程:
- 使用TF-IDF向量化(保留前1000个重要特征)
- 自动处理不同长度的文本
-
模型选择:
- 使用多项式朴素贝叶斯(适合处理离散特征和词频数据)
- 自动处理多分类问题
-
评估指标:
- 准确率
- 混淆矩阵
-
预测功能:
- 输出预测结果及概率分布
- 支持任意长度文本输入
输出示例
准确率: 1.00
混淆矩阵:
[[2 0]
[0 2]]
预测结果: {
'text': 'This movie was surprisingly good!',
'prediction': 'positive',
'positive_prob': 0.85,
'negative_prob': 0.15
}
改进建议
-
数据增强:
- 使用更大的数据集(如IMDB影评数据集)
- 添加数据平衡处理
-
特征优化:
- 尝试n-gram特征(bigram/trigram)
- 使用词干提取/词形还原
- 调整TF-IDF参数(max_features, min_df等)
-
模型优化:
- 尝试不同朴素贝叶斯变体(BernoulliNB)
- 加入交叉验证
- 进行超参数调优
-
扩展功能:
- 添加情感强度分析
- 支持多语言处理
- 部署为API服务
朴素贝叶斯虽然简单,但在情感分析任务中仍能提供不错的基线性能。实际应用中建议结合具体需求进行优化调整。