bert-emotion 是基于 BERT-Mini 的轻量级情感分析模型,专门针对短文本情感检测优化。该模型能够将文本分类到 13 种情感类别,包括 happiness、sadness、anger、love 等。模型大小仅约 20MB,参数约 6M,适合边缘设备和实时应用。
bert-emotion-ascend/
├── inference.py # 推理测试脚本
├── log.txt # 测试日志
├── README.md # 本文档
├── test_sample.txt # 测试样例
├── inference_result.json # 推理结果
└── precision_result.json # 精度测试结果docker exec -it test-modelagent bashsource /usr/local/Ascend/ascend-toolkit/set_env.sh模型文件位于 /data/ysws/agentsp/5-16/bert-emotion/boltuix/bert-emotion/ 目录下:
pip install transformers torch_npu -i https://pypi.huaweicloud.com/repository/pypi/simple/Run the inference script for emotion classification:
cd /data/ysws/agentsp/5-16/bert-emotion-ascend/
python3 inference.py --mode inference运行精度对比测试,验证 NPU 计算结果与 CPU 一致性:
cd /data/ysws/agentsp/5-16/bert-emotion-ascend/
python3 inference.py --mode precision_testcd /data/ysws/agentsp/5-16/bert-emotion-ascend/
python3 inference.py --mode all| 参数 | 说明 | 默认值 |
|---|---|---|
--mode | 测试模式: inference, precision_test 或 all | all |
| 指标 | 实测值 | 阈值 | 状态 |
|---|---|---|---|
| 最大相对误差 | 0.0110% | < 1.00% | PASS |
| 最大绝对误差 | 7.37e-04 | - | - |
| CPU 推理时间 | 0.021s | - | - |
| NPU 推理时间 | 0.008s | - | - |
| 加速比 | 2.46x | > 1x | PASS |
| 预测标签一致性 | 完全一致 | - | PASS |
| 操作 | 耗时 |
|---|---|
| NPU 推理时间 (3 句) | 0.236s |
| 精度测试 CPU 时间 | 0.021s |
| 精度测试 NPU 时间 | 0.008s |
| 输入文本 | 预测情感 |
|---|---|
| "I am so happy today! Everything is going great!" | happiness |
| "This is really disappointing and makes me sad." | sadness |
| "I can't believe it! That's amazing news!" | surprise |
结果: 模型正确识别了文本中的情感类别。
============================================================
BERT-Emotion NPU Test
Model: boltuix/bert-emotion
Output: /data/ysws/agentsp/5-16/bert-emotion-ascend
============================================================
============================================================
BERT-Emotion Inference Test (NPU)
============================================================
Device: npu:0
Model: /data/ysws/agentsp/5-16/bert-emotion/boltuix/bert-emotion
Loading tokenizer...
Loading model...
Loading weights: 100%|██████████| 73/73 [00:00<00:00, 4817.25it/s]
Model loaded successfully
Input texts: ['I am so happy today! Everything is going great!', 'This is really disappointing and makes me sad.', "I can't believe it! That's amazing news!"]
Input shape: torch.Size([3, 15])
Logits shape: torch.Size([3, 13])
Predictions: [5, 0, 3]
Labels: ['happiness', 'sadness', 'surprise']
Inference time: 0.236s
Inference result saved to /data/ysws/agentsp/5-16/bert-emotion-ascend/inference_result.json
============================================================
Precision Test (CPU vs NPU)
============================================================
Using device: npu:0
Loading tokenizer...
Loading model on CPU...
Loading weights: 100%|██████████| 73/73 [00:00<00:00, 4589.30it/s]
Loading model on npu:0...
Loading weights: 100%|██████████| 73/73 [00:00<00:00, 4248.72it/s]
Running inference on CPU...
Running inference on NPU...
CPU inference time: 0.021s
NPU inference time: 0.008s
Speedup: 2.46x
Max absolute error: 7.374287e-04
Max relative error: 0.0110% (threshold: 1.0%)
CPU predictions: [5] -> happiness
NPU predictions: [5] -> happiness
Predictions match: True
Status: PASS
Precision result saved to /data/ysws/agentsp/5-16/bert-emotion-ascend/precision_result.json
============================================================
Creating Test Sample
============================================================
Saved test sample: /data/ysws/agentsp/5-16/bert-emotion-ascend/test_sample.txt
============================================================
Test Complete!
============================================================import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
MODEL_DIR = "/data/ysws/agentsp/5-16/bert-emotion/boltuix/bert-emotion"
tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_DIR)
model = model.to("npu:0").eval()
texts = ["I am so happy today!", "This is really disappointing."]
inputs = tokenizer(texts, return_tensors="pt", padding=True, truncation=True, max_length=128)
inputs = {k: v.to("npu:0") for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
predictions = torch.argmax(outputs.logits, dim=-1)
labels = [model.config.id2label[p.item()] for p in predictions]
print(labels)def detect_emotion(text):
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=128)
inputs = {k: v.to("npu:0") for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
prediction = torch.argmax(outputs.logits, dim=-1).item()
return model.config.id2label[prediction]
emotion = detect_emotion("I'm feeling really anxious about this.")
print(f"Detected emotion: {emotion}")| 情感 ID | 情感名称 |
|---|---|
| 0 | sadness |
| 1 | anger |
| 2 | love |
| 3 | surprise |
| 4 | fear |
| 5 | happiness |
| 6 | neutral |
| 7 | disgust |
| 8 | shame |
| 9 | guilt |
| 10 | confusion |
| 11 | desire |
| 12 | sarcasm |
从 config.json 提取的关键参数:
{
"model_type": "bert",
"hidden_size": 256,
"num_hidden_layers": 4,
"num_attention_heads": 4,
"intermediate_size": 1024,
"vocab_size": 30522,
"max_position_embeddings": 512,
"attention_probs_dropout_prob": 0.1,
"hidden_dropout_prob": 0.1
}A: 检查 NPU 驱动是否正确安装。BERT-Emotion 模型在 CPU 和 NPU 上的输出完全一致,误差极小 (0.01%)。
A: 使用批处理可以提高吞吐量。NPU 推理非常快 (0.008s vs CPU 0.021s)。
A: 本模型专门针对英语文本的情感分析。如需中文支持,请查找对应语言的情感分析模型。
本项目遵循 Apache-2.0 许可证