Downloads · 30 days
0
CHristianREEVEE/sentiment-bert
sentiment-bert is a machine learning model from CHristianREEVEE. Use it for the machine learning task on the model card, and read the license before you ship it in a product.
基于预训练 BERT 的 IMDB 影评二分类情感分析项目,包含模型训练、评估可视化、RESTful API 服务与 Docker 部署全流程。
Downloads · 30 days
0
Access
Public
Updated Aug 4, 2026
Repo size
—
Likes
0
Public
Click a slice to open those files.
.py29.5 KB · 61%
From the Hugging Face model README
基于预训练 BERT 的 IMDB 影评二分类情感分析项目,包含模型训练、评估可视化、RESTful API 服务与 Docker 部署全流程。
sentiment-analysis-bert/
├── model.py # BERT + Dropout + Linear 模型定义
├── train.py # 训练与评估主流程
├── visualize.py # 可视化分析模块
├── main.py # FastAPI RESTful 服务
├── requirements.txt # Python 依赖
├── Dockerfile # Docker 部署文件
├── data/
│ └── imdb_dataset.csv # IMDB 数据集 (需自行放置)
└── outputs/
├── best_model.pt # 训练后的最佳权重
├── eval_results.json
├── training_history.csv
└── figures/ # 可视化图表
| 模块 | 技术 |
|---|---|
| 预训练模型 | bert-base-uncased (HuggingFace Transformers) |
| 深度学习框架 | PyTorch + AdamW + Linear Warmup Scheduler |
| 数据处理 | Pandas + Scikit-learn |
| 可视化 | Matplotlib + Seaborn |
| API 服务 | FastAPI + Uvicorn |
| 部署 | Docker / Render / Hugging Face Spaces |
# 克隆仓库
git clone https://github.com/your-username/sentiment-analysis-bert.git
cd sentiment-analysis-bert
# 安装依赖
pip install -r requirements.txt
将 IMDB 数据集放置到 data/imdb_dataset.csv,CSV 需包含两列:
| review | sentiment |
|---|---|
| This movie is fantastic! | positive |
| Boring and predictable. | negative |
数据集来源: IMDB Dataset of 50K Movie Reviews (Kaggle)
python train.py --epochs 3 --batch_size 16 --lr 2e-5 --max_length 256
可选参数:
| 参数 | 默认值 | 说明 |
|---|---|---|
--data_path | data/imdb_dataset.csv | 数据集路径 |
--model_name | bert-base-uncased | 预训练模型名称 |
--max_length | 256 | 文本编码最大长度 |
--batch_size | 16 | 训练批大小 |
--epochs | 3 | 训练轮数 |
--lr | 2e-5 | 学习率 |
--weight_decay | 1e-4 | 权重衰减 |
--warmup_ratio | 0.1 | Warmup 比例 |
--dropout | 0.3 | Dropout 概率 |
--output_dir | outputs | 输出目录 |
训练完成后,outputs/ 下会生成:
best_model.pt — 最佳模型权重eval_results.json — 验证集评估结果(含混淆矩阵、预测概率)training_history.csv — 每个 epoch 的 loss/acc 记录预期输出:
训练完成!最佳验证准确率: 0.93xx
模型权重: outputs/best_model.pt
评估结果: outputs/eval_results.json
python visualize.py --results outputs/eval_results.json --data data/imdb_dataset.csv --output_dir outputs/figures
生成图表:
| 文件 | 内容 |
|---|---|
confusion_matrix.png | 混淆矩阵 Heatmap |
confidence_distribution.png | 预测置信度分布直方图 |
length_vs_sentiment.png | 文本长度与情感极性关系图 |
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
访问交互式文档: http://localhost:8000/docs
# 构建镜像
docker build -t sentiment-bert .
# 运行容器
docker run -p 8000:8000 sentiment-bert
GET /health健康探针接口。
curl -X GET http://localhost:8000/health
响应:
{
"status": "healthy",
"model_loaded": true,
"device": "cpu"
}
POST /predict批量情感预测接口,接收文本列表,返回每个文本的情感标签与置信度。
curl -X POST http://localhost:8000/predict \
-H "Content-Type: application/json" \
-d '{
"texts": [
"This movie is absolutely fantastic! The acting was brilliant.",
"Terrible plot, boring characters, total waste of time.",
"An average film, nothing special but not terrible either."
]
}'
响应:
{
"results": [
{
"text": "This movie is absolutely fantastic! The acting was brilliant.",
"label": "positive",
"confidence": 0.9987
},
{
"text": "Terrible plot, boring characters, total waste of time.",
"label": "negative",
"confidence": 0.9973
},
{
"text": "An average film, nothing special but not terrible either.",
"label": "negative",
"confidence": 0.7231
}
],
"total": 3
}
Python 调用示例:
import requests
response = requests.post(
"http://localhost:8000/predict",
json={"texts": ["I love this film!", "Disappointing and dull."]}
)
print(response.json())
Input Text
│
▼
BertTokenizer (max_length=256)
│
▼
BERT Base Encoder (bert-base-uncased)
│
▼
[CLS] Token Hidden State (768-dim)
│
▼
Dropout (p=0.3)
│
▼
Linear Layer (768 → 2)
│
▼
Softmax → {negative, positive}
| 指标 | 目标值 | 实际值 |
|---|---|---|
| Validation Accuracy | ≥ 90% | ~93% |
| Precision | - | ~0.93 |
| Recall | - | ~0.93 |
| F1-Score | - | ~0.93 |
pip install -r requirements.txtuvicorn main:app --host 0.0.0.0 --port $PORToutputs/best_model.pt 已包含在仓库中app.py 中使用 Gradio 封装 /predict 接口MIT