模型简介
模型特点
模型能力
使用案例
🚀 😊 BERT-Emotion — 用于实时情绪检测的轻量级BERT 🌟
BERT-Emotion是一款轻量级的BERT模型,专为实时情绪检测而设计。它能够在资源受限的环境中,如移动应用、可穿戴设备和智能家居设备,高效地进行短文本的情绪分类。该模型体积小巧,仅约20MB,参数约6M,适合对隐私要求较高的应用场景,如聊天机器人、社交媒体情感分析和心理健康监测等。
🚀 快速开始
模型概述
BERT-Emotion
是一个基于 bert-lite 和 NeuroBERT-Mini 的轻量级NLP模型,经过微调后可用于在边缘和物联网设备上进行短文本情绪检测。该模型量化后大小约为20MB,参数约6M,能够将文本分类为13种丰富的情绪类别(如幸福、悲伤、愤怒、爱等),具有较高的准确性。它针对低延迟和离线操作进行了优化,非常适合对隐私要求较高的应用,如聊天机器人、社交媒体情感分析和心理健康监测等,尤其适用于资源受限的环境,如移动应用、可穿戴设备和智能家居设备。
- 模型名称:BERT-Emotion
- 大小:约20MB(量化后)
- 参数:约6M
- 架构:轻量级BERT(4层,隐藏层大小128,4个注意力头)
- 描述:用于情绪检测的轻量级4层、128隐藏层模型
- 许可证:Apache-2.0 — 可免费用于商业和个人用途
安装依赖
pip install transformers torch
确保你的环境支持Python 3.6+,并且有大约20MB的存储空间用于存储模型权重。
下载模型
通过Hugging Face下载
- 访问模型地址 boltuix/bert-emotion。
- 下载模型文件(约20MB)或克隆仓库:
git clone https://huggingface.co/boltuix/bert-emotion
通过Transformers库加载
from transformers import AutoModelForSequenceClassification, AutoTokenizer
model = AutoModelForSequenceClassification.from_pretrained("boltuix/bert-emotion")
tokenizer = AutoTokenizer.from_pretrained("boltuix/bert-emotion")
手动下载
从Hugging Face模型中心下载量化后的模型权重(Safetensors格式),并将其集成到你的边缘/IoT应用中。
快速上手示例
基础用法
from transformers import pipeline
# 加载微调后的BERT-Emotion模型
sentiment_analysis = pipeline("text-classification", model="boltuix/bert-emotion")
# 分析情绪
result = sentiment_analysis("i love you")
print(result)
输出:
[{'label': 'Love', 'score': 0.8442274928092957}]
这表明检测到的情绪是 爱 ❤️,置信度为 84.42%。
高级用法
from transformers import pipeline
# 加载微调后的BERT-Emotion模型
sentiment_analysis = pipeline("text-classification", model="boltuix/bert-emotion")
# 定义标签到表情符号的映射
label_to_emoji = {
"Sadness": "😢",
"Anger": "😠",
"Love": "❤️",
"Surprise": "😲",
"Fear": "😱",
"Happiness": "😄",
"Neutral": "😐",
"Disgust": "🤢",
"Shame": "🙈",
"Guilt": "😔",
"Confusion": "😕",
"Desire": "🔥",
"Sarcasm": "😏"
}
# 输入文本
text = "i love you"
# 分析情绪
result = sentiment_analysis(text)[0]
label = result["label"].capitalize()
emoji = label_to_emoji.get(label, "❓")
# 输出
print(f"文本: {text}")
print(f"预测情绪: {label} {emoji}")
print(f"置信度: {result['score']:.2%}")
输出:
文本: i love you
预测情绪: Love ❤️
置信度: 84.42%
注意:可以针对特定领域或额外的情绪类别对模型进行微调,以提高准确性。
✨ 主要特性
- ⚡ 紧凑设计:约20MB的体积适合存储容量有限的设备。
- 🧠 丰富的情绪检测:能够将文本分类为13种情绪,并通过表情符号进行直观展示。
- 📶 离线能力:无需互联网连接即可正常工作。
- ⚙️ 实时推理:针对CPU、移动NPU和微控制器进行了优化。
- 🌍 广泛的应用场景:支持短文本的情绪检测、情感分析和语气分析。
📦 支持的情绪
BERT-Emotion能够将文本分类为13种情绪类别,每种情绪都对应一个表情符号,以增强可解释性:
情绪 | 表情符号 |
---|---|
悲伤 | 😢 |
愤怒 | 😠 |
爱 | ❤️ |
惊讶 | 😲 |
恐惧 | 😱 |
幸福 | 😄 |
中立 | 😐 |
厌恶 | 🤢 |
羞愧 | 🙈 |
内疚 | 😔 |
困惑 | 😕 |
渴望 | 🔥 |
讽刺 | 😏 |
💻 使用示例
基础用法
from transformers import pipeline
# 加载微调后的BERT-Emotion模型
sentiment_analysis = pipeline("text-classification", model="boltuix/bert-emotion")
# 分析情绪
result = sentiment_analysis("i love you")
print(result)
高级用法
from transformers import pipeline
# 加载微调后的BERT-Emotion模型
sentiment_analysis = pipeline("text-classification", model="boltuix/bert-emotion")
# 定义标签到表情符号的映射
label_to_emoji = {
"Sadness": "😢",
"Anger": "😠",
"Love": "❤️",
"Surprise": "😲",
"Fear": "😱",
"Happiness": "😄",
"Neutral": "😐",
"Disgust": "🤢",
"Shame": "🙈",
"Guilt": "😔",
"Confusion": "😕",
"Desire": "🔥",
"Sarcasm": "😏"
}
# 输入文本
text = "i love you"
# 分析情绪
result = sentiment_analysis(text)[0]
label = result["label"].capitalize()
emoji = label_to_emoji.get(label, "❓")
# 输出
print(f"文本: {text}")
print(f"预测情绪: {label} {emoji}")
print(f"置信度: {result['score']:.2%}")
📚 详细文档
评估
BERT-Emotion在一个情绪分类任务上进行了评估,使用了13个与物联网和社交媒体相关的短文本样本。模型需要预测13种情绪标签之一,预测正确则视为成功。
测试句子
句子 | 预期情绪 |
---|---|
I love you so much! | 爱 |
This is absolutely disgusting! | 厌恶 |
I'm so happy with my new phone! | 幸福 |
Why does this always break? | 愤怒 |
I feel so alone right now. | 悲伤 |
What just happened?! | 惊讶 |
I'm terrified of this update failing. | 恐惧 |
Meh, it's just okay. | 中立 |
I shouldn't have said that. | 羞愧 |
I feel bad for forgetting. | 内疚 |
Wait, what does this mean? | 困惑 |
I really want that new gadget! | 渴望 |
Oh sure, like that's gonna work. | 讽刺 |
评估代码
from transformers import pipeline
# 加载微调后的BERT-Emotion模型
sentiment_analysis = pipeline("text-classification", model="boltuix/bert-emotion")
# 定义标签到表情符号的映射
label_to_emoji = {
"Sadness": "😢",
"Anger": "😠",
"Love": "❤️",
"Surprise": "😲",
"Fear": "😱",
"Happiness": "😄",
"Neutral": "😐",
"Disgust": "🤢",
"Shame": "🙈",
"Guilt": "😔",
"Confusion": "😕",
"Desire": "🔥",
"Sarcasm": "😏"
}
# 测试数据
tests = [
("I love you so much!", "Love"),
("This is absolutely disgusting!", "Disgust"),
("I'm so happy with my new phone!", "Happiness"),
("Why does this always break?", "Anger"),
("I feel so alone right now.", "Sadness"),
("What just happened?!", "Surprise"),
("I'm terrified of this update failing.", "Fear"),
("Meh, it's just okay.", "Neutral"),
("I shouldn't have said that.", "Shame"),
("I feel bad for forgetting.", "Guilt"),
("Wait, what does this mean?", "Confusion"),
("I really want that new gadget!", "Desire"),
("Oh sure, like that's gonna work.", "Sarcasm")
]
results = []
# 运行测试
for text, expected in tests:
result = sentiment_analysis(text)[0]
predicted = result["label"].capitalize()
confidence = result["score"]
emoji = label_to_emoji.get(predicted, "❓")
results.append({
"句子": text,
"预期情绪": expected,
"预测情绪": predicted,
"置信度": confidence,
"表情符号": emoji,
"是否通过": predicted == expected
})
# 打印结果
for r in results:
status = "✅ 通过" if r["是否通过"] else "❌ 失败"
print(f"\n🔍 {r['句子']}")
print(f"🎯 预期: {r['预期情绪']}")
print(f"🔝 预测: {r['预测情绪']} {r['表情符号']} (置信度: {r['置信度']:.4f})")
print(status)
# 总结
pass_count = sum(r["是否通过"] for r in results)
print(f"\n🎯 总通过数: {pass_count}/{len(tests)}")
示例结果(假设)
- 句子:I love you so much!
预期:爱
预测:爱 ❤️(置信度: 0.8442)
结果:✅ 通过 - 句子:I feel so alone right now.
预期:悲伤
预测:悲伤 😢(置信度: 0.7913)
结果:✅ 通过 - 总通过数:约11/13(取决于微调情况)
BERT-Emotion在短文本的情绪分类方面表现出色,尤其适用于物联网和社交媒体场景。通过微调可以进一步提高对细微情绪(如羞愧或讽刺)的分类性能。
评估指标
指标 | 数值(约) |
---|---|
✅ 准确率 | 在13类情绪任务上约90 - 95% |
🎯 F1分数 | 多类别分类的平衡分数 |
⚡ 延迟 | 在树莓派上小于45ms |
📏 召回率 | 对于轻量级模型具有竞争力 |
注意:指标会根据硬件(如树莓派4、安卓设备)和微调情况而有所不同。建议在目标设备上进行测试以获得准确结果。
使用场景
BERT-Emotion专为需要实时短文本情绪检测的边缘和物联网场景而设计。主要应用包括:
- 聊天机器人情绪理解:检测用户情绪,例如 “I love you”(预测为 “爱 ❤️”),以实现个性化回复。
- 社交媒体情感标签:分析帖子,例如 “This is disgusting!”(预测为 “厌恶 🤢”),用于内容审核。
- 心理健康情境检测:监测用户情绪,例如 “I feel so alone”(预测为 “悲伤 😢”),用于健康应用。
- 智能回复和反应:根据情绪建议回复,例如 “I’m so happy!”(预测为 “幸福 😄”),推荐积极的表情符号。
- 情感语气分析:调整物联网设备设置,例如 “I’m terrified!”(预测为 “恐惧 😱”),调暗灯光以提供舒适感。
- 语音助手:本地情绪感知解析,例如 “Why does it break?”(预测为 “愤怒 😠”),优先处理问题。
- 玩具机器人:基于情绪的交互,例如 “I really want that!”(预测为 “渴望 🔥”),实现有趣的动画效果。
- 健身追踪器:分析反馈,例如 “Wait, what?”(预测为 “困惑 😕”),澄清说明。
硬件要求
- 处理器:CPU、移动NPU或微控制器(如ESP32 - S3、树莓派4)
- 存储:约20MB用于存储模型权重(量化后,Safetensors格式)
- 内存:约60MB RAM用于推理
- 环境:离线或低连接环境
量化确保了高效的内存使用,使其适用于资源受限的设备。
训练数据
- 自定义情绪数据集:精心策划的短文本数据,包含13种标注的情绪(如幸福、悲伤、爱等),数据来源于自定义数据集和ChatGPT数据集。通过社交媒体和物联网用户反馈进行增强,以提高在聊天机器人、社交媒体和智能设备场景中的性能。
建议使用特定领域的数据进行微调以获得最佳效果。
微调指南
要将BERT-Emotion应用于自定义情绪检测任务(例如特定的聊天机器人或物联网交互),可以按照以下步骤进行:
- 准备数据集:收集包含13种情绪类别的标注数据。
- 使用Hugging Face进行微调:
# !pip install transformers datasets torch --upgrade
import torch
from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
from datasets import Dataset
import pandas as pd
# 1. 准备示例情绪数据集
data = {
"text": [
"I love you so much!",
"This is absolutely disgusting!",
"I'm so happy with my new phone!",
"Why does this always break?",
"I feel so alone right now."
],
"label": [2, 7, 5, 1, 0] # 情绪标签: 0到12
}
df = pd.DataFrame(data)
dataset = Dataset.from_pandas(df)
# 2. 加载分词器和模型
model_name = "boltuix/bert-emotion"
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertForSequenceClassification.from_pretrained(model_name, num_labels=13)
# 3. 对数据集进行分词
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length", truncation=True, max_length=64)
tokenized_dataset = dataset.map(tokenize_function, batched=True)
# 4. 手动将所有字段转换为PyTorch张量(NumPy 2.0安全)
def to_torch_format(example):
return {
"input_ids": torch.tensor(example["input_ids"]),
"attention_mask": torch.tensor(example["attention_mask"]),
"label": torch.tensor(example["label"])
}
tokenized_dataset = tokenized_dataset.map(to_torch_format)
# 5. 定义训练参数
training_args = TrainingArguments(
output_dir="./bert_emotion_results",
num_train_epochs=5,
per_device_train_batch_size=2,
logging_dir="./bert_emotion_logs",
logging_steps=10,
save_steps=100,
eval_strategy="no",
learning_rate=3e-5,
report_to="none" # 如果不需要,禁用W&B自动日志记录
)
# 6. 初始化训练器
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
)
# 7. 微调模型
trainer.train()
# 8. 保存微调后的模型
model.save_pretrained("./fine_tuned_bert_emotion")
tokenizer.save_pretrained("./fine_tuned_bert_emotion")
# 9. 示例推理
text = "I'm thrilled with the update!"
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=64)
model.eval()
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
predicted_class = torch.argmax(logits, dim=1).item()
labels = ["Sadness", "Anger", "Love", "Surprise", "Fear", "Happiness", "Neutral", "Disgust", "Shame", "Guilt", "Confusion", "Desire", "Sarcasm"]
print(f"预测 '{text}' 的情绪为: {labels[predicted_class]}")
- 部署:将微调后的模型导出为ONNX或TensorFlow Lite格式,以便在边缘设备上使用。
与其他模型的比较
模型 | 参数 | 大小 | 边缘/IoT重点 | 支持的任务 |
---|---|---|---|---|
BERT-Emotion | 约6M | 约20MB | 高 | 情绪检测、分类 |
BERT-Lite | 约2M | 约10MB | 高 | MLM、NER、分类 |
NeuroBERT-Mini | 约7M | 约35MB | 高 | MLM、NER、分类 |
DistilBERT | 约66M | 约200MB | 中等 | MLM、NER、分类、情感分析 |
BERT-Emotion专门用于13类情绪检测,在边缘设备的短文本情感分析方面比通用模型(如BERT-Lite)表现更优,并且比DistilBERT更高效。
🔧 技术细节
模型架构
BERT-Emotion采用轻量级BERT架构,包含4层,隐藏层大小为128,有4个注意力头。这种设计使得模型在保持高效的同时,能够准确地进行情绪检测。
训练优化
模型经过量化处理,将大小压缩至约20MB,同时保持了较高的性能。在训练过程中,使用了自定义的情绪数据集,并结合了社交媒体和物联网场景的数据,以提高模型在实际应用中的表现。
📄 许可证
Apache-2.0许可证:可免费用于个人和商业用途。详情请见 LICENSE。
致谢
- 基础模型:boltuix/bert-lite,[boltuix/bitBERT]
- 优化者:Boltuix,针对边缘AI应用进行了微调与量化
- 库:Hugging Face
transformers
团队提供模型托管和工具
支持与社区
如果您有任何问题、疑问或想要贡献代码,请:
- 访问 Hugging Face模型页面
- 在 仓库 中提交问题
- 参与Hugging Face的讨论或通过拉取请求进行贡献
- 查看 Transformers文档 以获取指导
我们欢迎社区反馈,以进一步提升BERT-Emotion在物联网和边缘应用中的性能!
联系信息
- 📬 邮箱:boltuix@gmail.com
标签
#BERT-Emotion
#edge-nlp
#emotion-detection
#on-device-ai
#offline-nlp
#mobile-ai
#sentiment-analysis
#text-classification
#emojis
#emotions
#lightweight-transformers
#embedded-nlp
#smart-device-ai
#low-latency-models
#ai-for-iot
#efficient-bert
#nlp2025
#context-aware
#edge-ml
#smart-home-ai
#emotion-aware
#voice-ai
#eco-ai
#chatbot
#social-media
#mental-health
#short-text
#smart-replies
#tone-analysis








