[机器学习]朴素贝叶斯(微博评论情感分类)

160 阅读2分钟

以下是一个基于朴素贝叶斯的中文微博评论分类的完整Python代码示例,包含数据预处理、特征提取和模型训练全流程:

# -*- coding: utf-8 -*-
import jieba
import numpy as np
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.pipeline import make_pipeline

# 示例数据集(需要替换为你的真实数据)
# 格式:[(带标签的文本), ...] 0代表负面 1代表正面
comments = [
    ("这个产品真的太差了,完全不好用!", 0),
    ("非常满意的购物体验,推荐大家购买", 1),
    ("服务态度糟糕,不会再来了", 0),
    ("质量超出预期,物超所值", 1),
    ("物流慢得让人无法接受", 0),
    ("包装精美,使用方便", 1)
]

# 停用词列表(需要准备自己的停用词文件)
stopwords = set(["的", "了", "是", "就", "都", "也", "在", "和", "吗", "啊"])

# 中文分词函数
def chinese_tokenizer(text):
    words = jieba.lcut(text)
    return [word for word in words if word not in stopwords and len(word) > 1]

# 准备数据集
X = [comment[0] for comment in comments]
y = [comment[1] for comment in comments]

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建处理管道:TF-IDF向量化 + 朴素贝叶斯分类器
pipeline = make_pipeline(
    TfidfVectorizer(tokenizer=chinese_tokenizer),
    MultinomialNB()
)

# 训练模型
pipeline.fit(X_train, y_train)

# 评估模型
y_pred = pipeline.predict(X_test)
print("测试集准确率:", pipeline.score(X_test, y_test))
print("\n分类报告:")
print(classification_report(y_test, y_pred))

# 预测新样本
new_comments = [
    "这次体验太棒了!",
    "非常失望,绝对不会再买",
    "一般般,没什么特别的感觉"
]

predictions = pipeline.predict(new_comments)
sentiments = ["负面", "正面"]

for text, pred in zip(new_comments, predictions):
    print(f"'{text}' --> {sentiments[pred]}")

代码说明:

  1. 数据预处理
  • 使用结巴分词进行中文分词
  • 去除停用词和单字词
  • 需要自行准备完整的停用词表文件
  1. 特征提取
  • 使用TF-IDF进行文本向量化
  • 自动过滤低频词(默认min_df=1)
  1. 模型构建
  • 使用多项式朴素贝叶斯分类器
  • 通过Pipeline封装处理流程
  1. 扩展建议
  • 准备更大的标注数据集(至少1000+条)
  • 添加更完整的停用词表
  • 尝试添加文本清洗步骤(去除特殊符号、表情等)
  • 考虑使用BERT等预训练模型提升效果

需要安装的依赖库:

``bash pip install jieba scikit-learn


实际应用时需要:

1.  准备标注好的数据集(推荐至少1000条以上)
1.  准备完整的中文停用词表
1.  可能需要调整的特征工程参数:

-   TF-IDF的最大特征数(max_features)
-   词频阈值(min_df/max_df)
-   添加n-gram特征
-   调整朴素贝叶斯的平滑参数alpha

如果需要处理更大的数据集或更复杂的场景,可以考虑:

-   使用深度学习模型(如TextCNN、LSTM)
-   引入预训练词向量
-   增加数据增强策略
-   使用集成学习方法