Views
No views yet
videomae-large-finetuned-UCF-Crime-datasetMCG-NJU/videomae-large model, specifically adapted for video classification tasks on the UCF Crime dataset. It is designed to classify various activities and events, including normal and anomalous behaviors such as burglary, vandalism, or fighting, based on video input.MCG-NJU/videomae-largesample_data folder1import os
2import torch
3import cv2
4import numpy as np
5from torchvision import transforms
6from torch.utils.data import Dataset, DataLoader
7from transformers import VideoMAEForVideoClassification
8
9# Define video directory
10video_folder = "sample_data"
11
12# Define class mapping
13class_mapping = {
14 "Abuse": 0, "Arrest": 1, "Arson": 2, "Assault": 3, "Burglary": 4,
15 "Explosion": 5, "Fighting": 6, "Normal Videos": 7, "Road Accidents": 8,
16 "Robbery": 9, "Shooting": 10, "Shoplifting": 11, "Stealing": 12, "Vandalism": 13
17}
18reverse_mapping = {v: k for k, v in class_mapping.items()}
19
20# Load VideoMAE model
21model_name = "OPear/videomae-large-finetuned-UCF-Crime"
22device = "cuda" if torch.cuda.is_available() else "cpu"
23
24model = VideoMAEForVideoClassification.from_pretrained(
25 model_name,
26 label2id=class_mapping,
27 id2label=reverse_mapping,
28 ignore_mismatched_sizes=True,
29).to(device)
30model.eval()
31
32# Video processing function
33def load_video_frames(video_path, num_frames=16, size=(224, 224)):
34 """
35 Load video frames from a given path and resize them to (224, 224).
36 Converts video into a tensor of shape [num_frames, 3, height, width].
37 """
38 cap = cv2.VideoCapture(video_path)
39 frames = []
40
41 total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
42 frame_indices = np.linspace(0, total_frames - 1, num_frames, dtype=int)
43
44 for i in range(total_frames):
45 ret, frame = cap.read()
46 if not ret:
47 break
48 if i in frame_indices:
49 frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
50 frame = cv2.resize(frame, size)
51 frames.append(frame)
52
53 cap.release()
54
55 if len(frames) < num_frames: # Pad if not enough frames
56 frames.extend([frames[-1]] * (num_frames - len(frames)))
57
58 frames = np.stack(frames, axis=0) # Shape: [num_frames, height, width, 3]
59 frames = torch.tensor(frames, dtype=torch.float32).permute(0, 3, 1, 2) / 255.0 # Normalize
60
61 return frames # Shape: [num_frames, 3, height, width]
62
63# Custom Dataset
64class VideoDataset(Dataset):
65 def __init__(self, video_folder):
66 self.video_files = [os.path.join(video_folder, f) for f in os.listdir(video_folder) if f.endswith(".mp4")]
67
68 def __len__(self):
69 return len(self.video_files)
70
71 def __getitem__(self, idx):
72 video_path = self.video_files[idx]
73 video_tensor = load_video_frames(video_path)
74 return {"video": video_tensor, "filename": os.path.basename(video_path)}
75
76# Load dataset
77test_dataset = VideoDataset(video_folder)
78test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False)
79
80# Run inference
81with torch.no_grad():
82 for idx, sample in enumerate(test_loader):
83 video_tensor = sample["video"].squeeze(0) # Remove batch dimension from DataLoader
84 video_tensor = video_tensor.unsqueeze(0).to(device) # Correct shape: [1, 3, num_frames, H, W]
85
86 # Forward pass
87 outputs = model(video_tensor)
88
89 # Get predictions
90 probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
91 predicted_label = torch.argmax(probs, dim=-1).item()
92
93 filename = sample["filename"][0]
94
95 print(f"Video {idx}: {filename} - Predicted label = {reverse_mapping[predicted_label]}")
96checkpoint-1112{
learning_rate: 5e-05,
train_batch_size: 4,
eval_batch_size: 4,
seed: 42,
gradient_accumulation_steps: 2,
total_train_batch_size: 8,
optimizer: Use adamw_torch with betas=(0.9,0.999) and epsilon=1e-08 and optimizer_args=No additional optimizer arguments,
lr_scheduler_type: linear,
lr_scheduler_warmup_ratio: 0.1,
training_steps: 13320,
mixed_precision_training: Native AMP
}1@article{videomae_large,
2 title={VideoMAE: Masked Autoencoders for Video Representation Learning},
3 author={MCG-NJU Team},
4 year={2024},
5 url={https://huggingface.co/MCG-NJU/videomae-large}
6}1@InProceedings{Sultani_2018_CVPR,
2author = {Sultani, Waqas and Chen, Chen and Shah, Mubarak},
3title = {Real-World Anomaly Detection in Surveillance Videos},
4booktitle = {The IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
5month = {June},
6year = {2018}
7}