BERT-Emotion is a lightweight NLP model derived from bert-mini and bert-micro, fine-tuned for short-text emotion detection on edge and IoT devices. With a quantized size of ~20MB and ~6M parameters, it classifies text into 13 rich emotional categories (e.g., Happiness, Sadness, Anger, Love) with high accuracy. Optimized for low-latency and offline operation, BERT-Emotion is ideal for privacy-first applications like chatbots, social media sentiment analysis, and mental health monitoring in resource-constrained environments such as mobile apps, wearables, and smart home devices.
1Text: i love you
2Predicted Emotion: Love ❤️
3Confidence: 84.42%
Note: Fine-tune the model for specific domains or additional emotion categories to improve accuracy.
Evaluation
BERT-Emotion was evaluated on an emotion classification task using 13 short-text samples relevant to IoT and social media contexts. The model predicts one of 13 emotion labels, with success defined as the correct label being predicted.
Test Sentences
Sentence
Expected Emotion
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
Evaluation Code
python
1from transformers import pipeline
23# Load the fine-tuned BERT-Emotion model4sentiment_analysis = pipeline("text-classification", model="boltuix/bert-emotion")56# Define label-to-emoji mapping7label_to_emoji ={8"Sadness":"😢",9"Anger":"😠",10"Love":"❤️",11"Surprise":"😲",12"Fear":"😱",13"Happiness":"😄",14"Neutral":"😐",15"Disgust":"🤢",16"Shame":"🙈",17"Guilt":"😔",18"Confusion":"😕",19"Desire":"🔥",20"Sarcasm":"😏"21}2223# Test data24tests =[25("I love you so much!","Love"),26("This is absolutely disgusting!","Disgust"),27("I'm so happy with my new phone!","Happiness"),28("Why does this always break?","Anger"),29("I feel so alone right now.","Sadness"),30("What just happened?!","Surprise"),31("I'm terrified of this update failing.","Fear"),32("Meh, it's just okay.","Neutral"),33("I shouldn't have said that.","Shame"),34("I feel bad for forgetting.","Guilt"),35("Wait, what does this mean?","Confusion"),36("I really want that new gadget!","Desire"),37("Oh sure, like that's gonna work.","Sarcasm")38]3940results =[]4142# Run tests43for text, expected in tests:44 result = sentiment_analysis(text)[0]45 predicted = result["label"].capitalize()46 confidence = result["score"]47 emoji = label_to_emoji.get(predicted,"❓")48 results.append({49"sentence": text,50"expected": expected,51"predicted": predicted,52"confidence": confidence,53"emoji": emoji,54"pass": predicted == expected
55})5657# Print results58for r in results:59 status ="✅ PASS"if r["pass"]else"❌ FAIL"60print(f"\n🔍 {r['sentence']}")61print(f"🎯 Expected: {r['expected']}")62print(f"🔝 Predicted: {r['predicted']}{r['emoji']} (Confidence: {r['confidence']:.4f})")63print(status)6465# Summary66pass_count =sum(r["pass"]for r in results)67print(f"\n🎯 Total Passed: {pass_count}/{len(tests)}")
Sample Results (Hypothetical)
Sentence: I love you so much! Expected: Love Predicted: Love ❤️ (Confidence: 0.8442) Result: ✅ PASS
Sentence: I feel so alone right now. Expected: Sadness Predicted: Sadness 😢 (Confidence: 0.7913) Result: ✅ PASS
Total Passed: ~11/13 (depends on fine-tuning).
BERT-Emotion excels in classifying a wide range of emotions in short texts, particularly in IoT and social media contexts. Fine-tuning can further improve performance on nuanced emotions like Shame or Sarcasm.
Evaluation Metrics
Metric
Value (Approx.)
✅ Accuracy
~90–95% on 13-class emotion tasks
🎯 F1 Score
Balanced for multi-class classification
⚡ Latency
<45ms on Raspberry Pi
📏 Recall
Competitive for lightweight models
Note: Metrics vary based on hardware (e.g., Raspberry Pi 4, Android devices) and fine-tuning. Test on your target device for accurate results.
Use Cases
BERT-Emotion is designed for edge and IoT scenarios requiring real-time emotion detection for short texts. Key applications include:
Chatbot Emotion Understanding: Detect user emotions, e.g., “I love you” (predicts “Love ❤️”) to personalize responses.
Social Media Sentiment Tagging: Analyze posts, e.g., “This is disgusting!” (predicts “Disgust 🤢”) for content moderation.
Mental Health Context Detection: Monitor user mood, e.g., “I feel so alone” (predicts “Sadness 😢”) for wellness apps.
Smart Replies and Reactions: Suggest replies based on emotions, e.g., “I’m so happy!” (predicts “Happiness 😄”) for positive emojis.
Emotional Tone Analysis: Adjust IoT device settings, e.g., “I’m terrified!” (predicts “Fear 😱”) to dim lights for comfort.
Voice Assistants: Local emotion-aware parsing, e.g., “Why does it break?” (predicts “Anger 😠”) to prioritize fixes.
Toy Robotics: Emotion-driven interactions, e.g., “I really want that!” (predicts “Desire 🔥”) for engaging animations.
Processors: CPUs, mobile NPUs, or microcontrollers (e.g., ESP32-S3, Raspberry Pi 4)
Storage: ~20MB for model weights (quantized, Safetensors format)
Memory: ~60MB RAM for inference
Environment: Offline or low-connectivity settings
Quantization ensures efficient memory usage, making it suitable for resource-constrained devices.
Trained On
Custom Emotion Dataset: Curated short-text data with 13 labeled emotions (e.g., Happiness, Sadness, Love), sourced from custom datasets and chatgpt-datasets. Augmented with social media and IoT user feedback to enhance performance in chatbot, social media, and smart device contexts.
Fine-tuning on domain-specific data is recommended for optimal results.
Fine-Tuning Guide
To adapt BERT-Emotion for custom emotion detection tasks (e.g., specific chatbot or IoT interactions):
Prepare Dataset: Collect labeled data with 13 emotion categories.
Fine-Tune with Hugging Face:
python
1# !pip install transformers datasets torch --upgrade23import torch
4from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
5from datasets import Dataset
6import pandas as pd
78# 1. Prepare the sample emotion dataset9 data ={10"text":[11"I love you so much!",12"This is absolutely disgusting!",13"I'm so happy with my new phone!",14"Why does this always break?",15"I feel so alone right now."16],17"label":[2,7,5,1,0]# Emotions: 0 to 1218}19 df = pd.DataFrame(data)20 dataset = Dataset.from_pandas(df)2122# 2. Load tokenizer and model23 model_name ="boltuix/bert-emotion"24 tokenizer = BertTokenizer.from_pretrained(model_name)25 model = BertForSequenceClassification.from_pretrained(model_name, num_labels=13)2627# 3. Tokenize the dataset28deftokenize_function(examples):29return tokenizer(examples["text"], padding="max_length", truncation=True, max_length=64)3031 tokenized_dataset = dataset.map(tokenize_function, batched=True)3233# 4. Manually convert all fields to PyTorch tensors (NumPy 2.0 safe)34defto_torch_format(example):35return{36"input_ids": torch.tensor(example["input_ids"]),37"attention_mask": torch.tensor(example["attention_mask"]),38"label": torch.tensor(example["label"])39}4041 tokenized_dataset = tokenized_dataset.map(to_torch_format)4243# 5. Define training arguments44 training_args = TrainingArguments(45 output_dir="./bert_emotion_results",46 num_train_epochs=5,47 per_device_train_batch_size=2,48 logging_dir="./bert_emotion_logs",49 logging_steps=10,50 save_steps=100,51 eval_strategy="no",52 learning_rate=3e-5,53 report_to="none"# Disable W&B auto-logging if not needed54)5556# 6. Initialize Trainer57 trainer = Trainer(58 model=model,59 args=training_args,60 train_dataset=tokenized_dataset,61)6263# 7. Fine-tune the model64 trainer.train()6566# 8. Save the fine-tuned model67 model.save_pretrained("./fine_tuned_bert_emotion")68 tokenizer.save_pretrained("./fine_tuned_bert_emotion")6970# 9. Example inference71 text ="I'm thrilled with the update!"72 inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=64)73 model.eval()74with torch.no_grad():75 outputs = model(**inputs)76 logits = outputs.logits
77 predicted_class = torch.argmax(logits, dim=1).item()7879 labels =["Sadness","Anger","Love","Surprise","Fear","Happiness","Neutral","Disgust","Shame","Guilt","Confusion","Desire","Sarcasm"]80print(f"Predicted emotion for '{text}': {labels[predicted_class]}")
Deploy: Export the fine-tuned model to ONNX or TensorFlow Lite for edge devices.
Comparison to Other Models
Model
Parameters
Size
Edge/IoT Focus
Tasks Supported
BERT-Emotion
~6M
~20MB
High
Emotion Detection, Classification
BERT-Lite
~2M
~10MB
High
MLM, NER, Classification
NeuroBERT-Mini
~7M
~35MB
High
MLM, NER, Classification
DistilBERT
~66M
~200MB
Moderate
MLM, NER, Classification, Sentiment
BERT-Emotion is specialized for 13-class emotion detection, offering superior performance for short-text sentiment analysis on edge devices compared to general-purpose models like BERT-Lite, while being significantly more efficient than DistilBERT.
Emotion Classification Models Comparison Report
This report summarizes the evaluation results of various emotion classification models, including accuracy, F1 score, model size, and download links.
Very long sentences failed all the models; improvements needed.
Model sizes are approximate based on repository file sizes.
Accuracy and F1 scores are computed on a custom test dataset containing both short and long sentences per emotion.
F1 Score is the weighted average.
For more details, see the evaluation script or contact the report maintainer.
Model Variants
BoltUIX offers a range of BERT-based models tailored to different performance and resource requirements. The boltuix/bert-mobile model is optimized for mobile and edge devices, offering strong performance with the ability to quantize to ~25 MB without significant loss. Below is a summary of available models:
Tier
Model ID
Size (MB)
Notes
Micro
boltuix/bert-micro
~15 MB
Smallest, blazing-fast, moderate accuracy
Mini
boltuix/bert-mini
~17 MB
Ultra-compact, fast, slightly better accuracy
Tinyplus
boltuix/bert-tinyplus
~20 MB
Slightly bigger, better capacity
Small
boltuix/bert-small
~45 MB
Good compact/accuracy balance
Mid
boltuix/bert-mid
~50 MB
Well-rounded mid-tier performance
Medium
boltuix/bert-medium
~160 MB
Strong general-purpose model
Large
boltuix/bert-large
~365 MB
Top performer below full-BERT
Pro
boltuix/bert-pro
~420 MB
Use only if max accuracy is mandatory
Mobile
boltuix/bert-mobile
~140 MB
Mobile-optimized; quantize to ~25 MB with no major loss