一、项目介绍
随着社交媒体数据日益丰富,评论情感分析已成为NLP领域重要应用之一。本文分享基于BERT预训练模型实现的YouTube评论情感分类项目。核心任务是自动识别评论为积极、消极或中性类别,并详细解析代码实现机制及复现流程。
二、依赖与环境要求
为保证结果完全复现,建议严格使用如下依赖版本:
- pandas==2.2.3
- numpy==2.1.2
- matplotlib==3.10.1
- transformers==4.51.3
- tqdm==4.67.1
- torch==2.7.0+cu128
- scikit-learn==1.6.1
三、核心技术原理
1. 数据处理与标签编码
- 读取CSV格式YouTube评论数据
- 清理缺失评论项,针对三类情感(negative/neutral/positive)进行标签编码(0/1/2)
- 分层随机划分训练集与验证集,保持分布均衡
2. 文本分词与BERT嵌入
- 初始化
BertTokenizer,选用bert-base-uncased英文基础模型 - 分词过程中对最大长度(常用:128)截断或填充,确保每条文本一致
- 大数据分批次处理,统计分词分布优化MAXLEN参数选择
3. 数据集封装与采样
- 定制PyTorch
Dataset类,批量生成模型输入 - 对类别失衡通过WeightedRandomSampler进行动态均衡,以防偏向"大类"标签
4. 模型架构
- 主体为
BertModel+ Dropout + 全连接层 - 分类头部(单层FC):输入BERT池化向量,输出三分类
- 损失函数采用加权CrossEntropyLoss(支持类别权重)
python
class BertClassifier(nn.Module):
def __init__(self, pretrained_model, num_classes, class_weights=None):
self.bert = BertModel.from_pretrained(pretrained_model)
self.dropout = nn.Dropout(0.3)
self.fc = nn.Linear(self.bert.config.hidden_size, num_classes)
self.loss_fn = nn.CrossEntropyLoss(weight=class_weights) if class_weights else nn.CrossEntropyLoss()
def forward(self, input_ids, attention_mask, labels=None):
pooled = self.bert(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state[:, 0]
x = self.dropout(pooled)
logits = self.fc(x)
if labels is not None:
loss = self.loss_fn(logits, labels)
return logits, loss
return logits
模型支持GPU装载,自动适配CUDA设备。
四、训练及评估流程
1. 随机种子和环境复现
为保证结果严格复现,设置如下随机种子:
python
import random, numpy as np, torch
seed = 42
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
确保每次训练结果一致且可追溯。
2. 训练与验证循环
- AdamW优化器,实验建议2-10 epoch依实际数据酌情增减
- 每轮输出Loss/Accuracy,利用Scikit-learn
classification_report及混淆矩阵评估模型性能 - 验证集准确率最终约0.8380,宏平均F1接近0.81,正负面检出率明显高于中性类别
3. 单条文本分类及批量测试
- 模型训练完毕后可直接单条评论预测,例如:
python
model.load_state_dict(torch.load('best_bertsentiment.pth'))
model.eval()
def predict(text):
encoding = tokenizer(text, truncation=True, padding='max_length', max_length=MAXLEN, return_tensors='pt')
input_ids = encoding['input_ids'].to(device)
attention_mask = encoding['attention_mask'].to(device)
with torch.no_grad():
logits = model(input_ids, attention_mask)
pred = logits.argmax(1).item()
return id2label[pred]
result = predict("I love this channel!") # 返回 positive
批量样例测试准确率约为80%。
五、项目复现与部署建议
1. 环境与依赖安装
按上述版本安装全部依赖库,推荐用Anaconda/Miniconda管理环境。
2. 数据准备与脚本运行
- 保证所有数据(如
YouTubeCommentsDataSet.csv)路径正确 - 推荐在GPU服务器运行,提高处理性能
- Jupyter Notebook或标准.py脚本均可复现完整流程
3. 推理与服务化
- 模型保存为
.pth文件,便于后续 Flask/FastAPI/onnxruntime等API部署 - Tokenizer与模型一同序列化,提升服务启动速度和推理效率
六、主要结果展示与评测
| 类别 | Precision | Recall | F1-score | 支持数 |
|---|---|---|---|---|
| negative | 0.81 | 0.74 | 0.77 | 467 |
| neutral | 0.64 | 0.89 | 0.75 | 925 |
| positive | 0.97 | 0.84 | 0.90 | 2281 |
- 验证集准确率:84%
- 预测性能最强为积极评论类别
- 支持批量/单条文本快速推理
七、总结与扩展
本项目结合最新BERT及transformers库,为多类社交评论情感分析提供了高效可复现方案。适合场景包括舆情监控、用户反馈自动聚类等。对于中文任务建议切换至中文BERT模型,流程完全兼容。欢迎技术交流与代码复现反馈!
如需转载请注明CSDN及原作者信息。