Views
No views yet
1transforms.Compose([
2 transforms.RandomResizedCrop(224, scale=(0.8, 1.0)),
3 transforms.RandomHorizontalFlip(),
4 transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3),
5 transforms.RandomRotation(10),
6])| Metric | Value |
|---|---|
| Training Accuracy | 94.2% |
| Validation F1-Score | 0.91 (weighted) |
| Inference Time (GPU) | ~45ms per face |
| Inference Time (CPU) | ~180ms per face |
| 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 |
1from transformers import BeitForImageClassification, AutoImageProcessor
2from PIL import Image
3import torch
4
5# Load model and processor
6model = BeitForImageClassification.from_pretrained("nihar245/student-engagement-beit")
7processor = AutoImageProcessor.from_pretrained("nihar245/student-engagement-beit")
8
9# Prepare image
10image = Image.open("student_face.jpg").convert("RGB")
11inputs = processor(images=image, return_tensors="pt")
12
13# Inference
14with torch.no_grad():
15 outputs = model(**inputs)
16 probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
17 pred_class = torch.argmax(probs, dim=-1).item()
18
19# Get prediction
20labels = ["Bored", "Confused", "Engaged", "Neutral"]
21print(f"Prediction: {labels[pred_class]} ({probs[0][pred_class]:.2%} confidence)")1from facenet_pytorch import MTCNN
2import cv2
3
4# Initialize face detector
5mtcnn = MTCNN(keep_all=True, device='cuda')
6
7# Detect faces
8frame = cv2.imread("classroom.jpg")
9boxes, _ = mtcnn.detect(frame)
10
11# Process each face
12for box in boxes:
13 x1, y1, x2, y2 = [int(b) for b in box]
14 face = frame[y1:y2, x1:x2]
15
16 # Convert to PIL and predict
17 face_pil = Image.fromarray(cv2.cvtColor(face, cv2.COLOR_BGR2RGB))
18 inputs = processor(images=face_pil, return_tensors="pt")
19
20 with torch.no_grad():
21 outputs = model(**inputs)
22 pred = torch.argmax(outputs.logits, dim=-1).item()
23
24 print(f"Face at {box}: {labels[pred]}")1import cv2
2
3cap = cv2.VideoCapture(0)
4
5while True:
6 ret, frame = cap.read()
7 if not ret:
8 break
9
10 # Detect faces
11 boxes, _ = mtcnn.detect(frame)
12
13 if boxes is not None:
14 for box in boxes:
15 x1, y1, x2, y2 = [int(b) for b in box]
16 face = frame[y1:y2, x1:x2]
17
18 # Predict engagement
19 face_pil = Image.fromarray(cv2.cvtColor(face, cv2.COLOR_BGR2RGB))
20 inputs = processor(images=face_pil, return_tensors="pt")
21
22 with torch.no_grad():
23 outputs = model(**inputs)
24 pred = torch.argmax(outputs.logits, dim=-1).item()
25
26 # Draw results
27 color = (0, 255, 0) if labels[pred] == "Engaged" else (0, 165, 255)
28 cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
29 cv2.putText(frame, labels[pred], (x1, y1-10),
30 cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2)
31
32 cv2.imshow('Engagement Detection', frame)
33 if cv2.waitKey(1) & 0xFF == ord('q'):
34 break
35
36cap.release()
37cv2.destroyAllWindows()1from transformers import TrainingArguments, Trainer
2
3training_args = TrainingArguments(
4 output_dir="./results",
5 eval_strategy="epoch",
6 save_strategy="epoch",
7 learning_rate=2e-5,
8 per_device_train_batch_size=8,
9 per_device_eval_batch_size=8,
10 num_train_epochs=7,
11 weight_decay=0.01,
12 load_best_model_at_end=True,
13 metric_for_best_model="f1",
14 save_total_limit=2,
15)
16
17trainer = Trainer(
18 model=model,
19 args=training_args,
20 train_dataset=train_dataset,
21 eval_dataset=val_dataset,
22 compute_metrics=compute_metrics,
23)
24
25trainer.train()1@misc{mehta2025studentengagement,
2 author = {Nihar Mehta},
3 title = {Student Engagement Detection using BEiT Vision Transformer},
4 year = {2025},
5 publisher = {HuggingFace},
6 howpublished = {\url{https://huggingface.co/nihar245/student-engagement-beit}},
7 note = {Fine-tuned from microsoft/beit-base-patch16-224-pt22k-ft22k}
8}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.