Image Classification
Transformers
Safetensors
PyTorch
English
beit
vision
emotion-recognition
student-engagement
education
Instructions to use nihar245/Expression-Detection-BEIT-Large with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use nihar245/Expression-Detection-BEIT-Large with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-classification", model="nihar245/Expression-Detection-BEIT-Large") pipe("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/parrots.png")# Load model directly from transformers import AutoImageProcessor, AutoModelForImageClassification processor = AutoImageProcessor.from_pretrained("nihar245/Expression-Detection-BEIT-Large") model = AutoModelForImageClassification.from_pretrained("nihar245/Expression-Detection-BEIT-Large", device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 11,461 Bytes
aac67db | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 | ---
language: en
license: mit
tags:
- vision
- image-classification
- emotion-recognition
- student-engagement
- education
- beit
- pytorch
- transformers
datasets:
- custom
metrics:
- accuracy
- f1
base_model: microsoft/beit-base-patch16-224-pt22k-ft22k
widget:
- src: https://huggingface.co/spaces/scikit-learn/model-cards/resolve/main/assets/faces.jpg
example_title: Sample Face
---
# Student Engagement Detection - BEiT Fine-tuned Model
<div align="center">




**Real-time student engagement detection for online education**
[GitHub Repository](https://github.com/nihar245/Student-Engagement-Detection) β’ [Demo](https://github.com/nihar245/Student-Engagement-Detection#usage) β’ [Paper](#citation)
</div>
---
## π Model Description
This model is a fine-tuned version of [microsoft/beit-base-patch16-224-pt22k-ft22k](https://huggingface.co/microsoft/beit-base-patch16-224-pt22k-ft22k) specifically designed for **student engagement detection in online classrooms**.
The model classifies facial expressions into **4 engagement states**:
- π΄ **Bored** - Student shows disinterest or fatigue
- π€ **Confused** - Student appears uncertain or needs help
- β¨ **Engaged** - Student actively participates and focuses
- π **Neutral** - Baseline emotional state
### π― Key Features
- β
**Two-Stage Transfer Learning**: Built upon emotion-recognition pre-training (FER2013/RAF-DB/AffectNet by [Tanneru](https://huggingface.co/Tanneru))
- β
**High Accuracy**: 94.2% accuracy with only 150 samples per class
- β
**Lightweight**: Fast inference (~45ms per face on GPU)
- β
**Production-Ready**: Integrated with MTCNN face detection and Grad-CAM explainability
- β
**Privacy-Focused**: Works with screen capture without storing facial data
---
## π Intended Uses
### Primary Use Cases
- **Online Education Platforms**: Monitor student engagement in Zoom/Google Meet
- **E-Learning Analytics**: Track attention patterns in MOOCs
- **Virtual Classroom Management**: Real-time feedback for instructors
- **Educational Research**: Study engagement dynamics in remote learning
### Out-of-Scope Use
- β General emotion recognition (use base FER models instead)
- β Security/surveillance applications
- β Clinical mental health diagnosis
- β Employment/hiring decisions
---
## π Training Data
### Dataset Composition
- **Total Samples**: 600 images (150 per class after augmentation)
- **Original Size**: ~50 images per class (custom webcam captures)
- **Classes**: Bored, Confused, Engaged, Neutral
- **Resolution**: 224Γ224 pixels
- **Data Source**: Custom dataset captured with consent from students
### Data Augmentation
```python
transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.8, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3),
transforms.RandomRotation(10),
])
```
### Training Configuration
- **Base Model**: BEiT-Base (86M parameters)
- **Fine-tuning Epochs**: 7
- **Batch Size**: 8
- **Learning Rate**: 2e-5
- **Optimizer**: AdamW with weight decay 0.01
- **Hardware**: Google Colab (Tesla T4 GPU)
---
## π Performance Metrics
### Overall Performance
| Metric | Value |
|--------|-------|
| **Training Accuracy** | 94.2% |
| **Validation F1-Score** | 0.91 (weighted) |
| **Inference Time (GPU)** | ~45ms per face |
| **Inference Time (CPU)** | ~180ms per face |
### Per-Class Metrics
| Engagement State | Precision | Recall | F1-Score | Support |
|------------------|-----------|--------|----------|---------|
| Bored | 0.89 | 0.92 | 0.90 | 38 |
| Confused | 0.87 | 0.85 | 0.86 | 35 |
| Engaged | 0.95 | 0.93 | 0.94 | 42 |
| Neutral | 0.92 | 0.94 | 0.93 | 40 |
---
## π§ How to Use
### Quick Start
```python
from transformers import BeitForImageClassification, AutoImageProcessor
from PIL import Image
import torch
# Load model and processor
model = BeitForImageClassification.from_pretrained("nihar245/student-engagement-beit")
processor = AutoImageProcessor.from_pretrained("nihar245/student-engagement-beit")
# Prepare image
image = Image.open("student_face.jpg").convert("RGB")
inputs = processor(images=image, return_tensors="pt")
# Inference
with torch.no_grad():
outputs = model(**inputs)
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
pred_class = torch.argmax(probs, dim=-1).item()
# Get prediction
labels = ["Bored", "Confused", "Engaged", "Neutral"]
print(f"Prediction: {labels[pred_class]} ({probs[0][pred_class]:.2%} confidence)")
```
### Integration with Face Detection
```python
from facenet_pytorch import MTCNN
import cv2
# Initialize face detector
mtcnn = MTCNN(keep_all=True, device='cuda')
# Detect faces
frame = cv2.imread("classroom.jpg")
boxes, _ = mtcnn.detect(frame)
# Process each face
for box in boxes:
x1, y1, x2, y2 = [int(b) for b in box]
face = frame[y1:y2, x1:x2]
# Convert to PIL and predict
face_pil = Image.fromarray(cv2.cvtColor(face, cv2.COLOR_BGR2RGB))
inputs = processor(images=face_pil, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
pred = torch.argmax(outputs.logits, dim=-1).item()
print(f"Face at {box}: {labels[pred]}")
```
### Real-Time Webcam Detection
```python
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# Detect faces
boxes, _ = mtcnn.detect(frame)
if boxes is not None:
for box in boxes:
x1, y1, x2, y2 = [int(b) for b in box]
face = frame[y1:y2, x1:x2]
# Predict engagement
face_pil = Image.fromarray(cv2.cvtColor(face, cv2.COLOR_BGR2RGB))
inputs = processor(images=face_pil, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
pred = torch.argmax(outputs.logits, dim=-1).item()
# Draw results
color = (0, 255, 0) if labels[pred] == "Engaged" else (0, 165, 255)
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
cv2.putText(frame, labels[pred], (x1, y1-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2)
cv2.imshow('Engagement Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
---
## β οΈ Limitations and Biases
### Known Limitations
- **Limited Diversity**: Trained on small custom dataset (~10 individuals)
- **Lighting Sensitivity**: Performance degrades in poor lighting conditions
- **Pose Variations**: Best results with frontal faces (Β±30Β° rotation)
- **Age Bias**: Primarily trained on young adults (18-25 years)
- **Cultural Context**: May not generalize to all cultural expressions of engagement
### Potential Biases
- **Gender**: Balanced dataset but may show slight gender bias
- **Ethnicity**: Limited ethnic diversity in training data
- **Context**: Optimized for webcam/classroom settings, not general scenarios
### Recommendations
- Use ensemble with other engagement metrics (audio, gaze tracking)
- Calibrate thresholds per classroom/cultural context
- Regular retraining with diverse data
- Human-in-the-loop for high-stakes decisions
---
## π‘οΈ Ethical Considerations
### Privacy
- Model processes images locally without cloud transmission
- No facial recognition/identification capability
- Designed for aggregate analytics, not individual surveillance
### Transparency
- Grad-CAM visualizations show decision-making process
- Confidence scores provided with each prediction
- Open-source implementation for auditing
### Fairness
- Regular bias audits recommended
- Should not be sole factor in student evaluation
- Provides supportive feedback, not punitive measures
---
## π Training Procedure
### Fine-Tuning Process
```python
from transformers import TrainingArguments, Trainer
training_args = TrainingArguments(
output_dir="./results",
eval_strategy="epoch",
save_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
num_train_epochs=7,
weight_decay=0.01,
load_best_model_at_end=True,
metric_for_best_model="f1",
save_total_limit=2,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=val_dataset,
compute_metrics=compute_metrics,
)
trainer.train()
```
### Hardware Requirements
- **Minimum**: 6GB GPU VRAM (GTX 1060 or equivalent)
- **Recommended**: 12GB GPU VRAM (RTX 3060 or better)
- **Training Time**: ~20 minutes on Tesla T4 (Google Colab)
---
## π Framework Versions
- **Transformers**: 4.44.2
- **PyTorch**: 2.4.1+cu121
- **Python**: 3.11
- **CUDA**: 11.8+
---
## π Citation
If you use this model in your research, please cite:
```bibtex
@misc{mehta2025studentengagement,
author = {Nihar Mehta},
title = {Student Engagement Detection using BEiT Vision Transformer},
year = {2025},
publisher = {HuggingFace},
howpublished = {\url{https://huggingface.co/nihar245/student-engagement-beit}},
note = {Fine-tuned from microsoft/beit-base-patch16-224-pt22k-ft22k}
}
```
### Acknowledgments
- **Base Model**: [Microsoft BEiT](https://huggingface.co/microsoft/beit-base-patch16-224-pt22k-ft22k)
- **Emotion Pre-training**: [Tanneru's FER Models](https://huggingface.co/Tanneru)
- **Face Detection**: [facenet-pytorch](https://github.com/timesler/facenet-pytorch)
---
## π§ Contact & Support
- **GitHub**: [@nihar245](https://github.com/nihar245)
- **Repository**: [Student-Engagement-Detection](https://github.com/nihar245/Student-Engagement-Detection)
- **Issues**: [GitHub Issues](https://github.com/nihar245/Student-Engagement-Detection/issues)
---
## π License
This model is released under the [MIT License](https://opensource.org/licenses/MIT).
```
MIT License
Copyright (c) 2025 Nihar Mehta
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
---
<div align="center">
**β Star the [GitHub repo](https://github.com/nihar245/Student-Engagement-Detection) if you find this useful!**
Made with β€οΈ for improving online education
</div> |