YAML Metadata Warning:empty or missing yaml metadata in repo card

Check out the documentation for more information.

BERT 文本情感分析与可视化系统

基于预训练 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

快速开始

1. 环境准备

# 克隆仓库
git clone https://github.com/your-username/sentiment-analysis-bert.git
cd sentiment-analysis-bert

# 安装依赖
pip install -r requirements.txt

2. 数据准备

将 IMDB 数据集放置到 data/imdb_dataset.csv,CSV 需包含两列:

review sentiment
This movie is fantastic! positive
Boring and predictable. negative

数据集来源: IMDB Dataset of 50K Movie Reviews (Kaggle)

3. 模型训练

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

4. 可视化分析

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 文本长度与情感极性关系图

5. 启动 API 服务

uvicorn main:app --host 0.0.0.0 --port 8000 --reload

访问交互式文档: http://localhost:8000/docs

6. Docker 部署

# 构建镜像
docker build -t sentiment-bert .

# 运行容器
docker run -p 8000:8000 sentiment-bert

API 接口文档

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

部署说明

Render 部署

  1. 在 Render 控制台创建新的 Web Service
  2. 连接 GitHub 仓库
  3. 配置:
    • Build Command: pip install -r requirements.txt
    • Start Command: uvicorn main:app --host 0.0.0.0 --port $PORT
  4. 确保训练好的 outputs/best_model.pt 已包含在仓库中

Hugging Face Spaces 部署

  1. 创建新的 Space (Gradio/Streamlit 类型)
  2. 上传项目文件
  3. app.py 中使用 Gradio 封装 /predict 接口

License

MIT

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support