File size: 7,619 Bytes
343b5d3 | 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 | import os
import cv2
import torch
import numpy as np
import pandas as pd
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from pytorchvideo.models.resnet import create_resnet
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm
# =========================
# CONFIG
# =========================
NUM_FRAMES = 16
IMG_SIZE = 112
BATCH_SIZE = 8
EPOCHS = 20
LR = 5e-5
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("π Using device:", DEVICE)
# =========================
# DATASET
# =========================
class AirLettersDataset(Dataset):
def __init__(self, csv_path, video_dir):
self.df = pd.read_csv(csv_path)
self.df.columns = self.df.columns.str.strip()
self.video_dir = video_dir
self.transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((IMG_SIZE, IMG_SIZE)), # β
no cropping issues
transforms.RandomHorizontalFlip(p=0.3),
transforms.RandomRotation(10),
transforms.ToTensor(),
transforms.Normalize([0.45]*3, [0.225]*3)
])
def __len__(self):
return len(self.df)
def get_label(self, label):
label = label.lower().strip()
try:
if "letter" in label:
char = label.split("letter")[1].strip()[0]
return ord(char.upper()) - ord('A')
elif "digit" in label:
digit = label.split("digit")[1].strip()[0]
return 26 + int(digit)
elif "doing nothing" in label:
return 36
else:
return 37
except:
return 37
def load_video(self, path):
cap = cv2.VideoCapture(path)
if not cap.isOpened():
return None
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total == 0:
cap.release()
return None
indices = np.linspace(0, total - 1, NUM_FRAMES).astype(int)
frames = []
for idx in indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
ret, frame = cap.read()
if ret and frame is not None:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(self.transform(frame))
cap.release()
if len(frames) == 0:
return None
while len(frames) < NUM_FRAMES:
frames.append(frames[-1])
return torch.stack(frames).permute(1, 0, 2, 3)
def __getitem__(self, idx):
for _ in range(5):
row = self.df.iloc[idx]
video_path = os.path.join(self.video_dir, row['filename'])
video = self.load_video(video_path)
if video is not None:
label = self.get_label(row['label'])
return video, label
idx = (idx + 1) % len(self.df)
raise RuntimeError("Too many bad videos")
# =========================
# MAIN
# =========================
def main():
train_csv = "train.csv"
val_csv = "val.csv"
test_csv = "test.csv"
video_dir = "videos"
train_set = AirLettersDataset(train_csv, video_dir)
val_set = AirLettersDataset(val_csv, video_dir)
test_set = AirLettersDataset(test_csv, video_dir)
train_loader = DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=4, pin_memory=True)
val_loader = DataLoader(val_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, pin_memory=True)
test_loader = DataLoader(test_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, pin_memory=True)
# =========================
# MODEL
# =========================
model = create_resnet(
input_channel=3,
model_depth=101,
model_num_class=38
).to(DEVICE)
# =========================
# LOAD PRETRAINED
# =========================
if os.path.exists("resnext200_airletters.pth"):
print("π¦ Loading pretrained weights...")
state_dict = torch.load("resnext200_airletters.pth", map_location=DEVICE)
model_dict = model.state_dict()
filtered_dict = {k: v for k, v in state_dict.items()
if k in model_dict and model_dict[k].shape == v.shape}
model_dict.update(filtered_dict)
model.load_state_dict(model_dict)
print("β
Pretrained loaded safely")
# =========================
# TRAIN SETUP
# =========================
criterion = nn.CrossEntropyLoss(label_smoothing=0.1)
optimizer = optim.Adam(model.parameters(), lr=LR)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)
scaler = torch.cuda.amp.GradScaler()
best_acc = 0
# =========================
# TRAIN LOOP
# =========================
for epoch in range(EPOCHS):
model.train()
correct, total, loss_sum = 0, 0, 0
loop = tqdm(train_loader, desc=f"π₯ Epoch {epoch+1}/{EPOCHS}")
for videos, labels in loop:
videos, labels = videos.to(DEVICE), labels.to(DEVICE)
optimizer.zero_grad()
# β
AMP
with torch.cuda.amp.autocast():
outputs = model(videos)
loss = criterion(outputs, labels)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
loss_sum += loss.item()
_, preds = torch.max(outputs, 1)
correct += (preds == labels).sum().item()
total += labels.size(0)
acc = 100 * correct / total
loop.set_postfix(loss=f"{loss.item():.4f}", acc=f"{acc:.2f}%")
scheduler.step()
train_acc = 100 * correct / total
print(f"\nπ Train Acc: {train_acc:.2f}%")
# =========================
# VALIDATION
# =========================
model.eval()
val_correct, val_total = 0, 0
with torch.no_grad():
for videos, labels in val_loader:
videos, labels = videos.to(DEVICE), labels.to(DEVICE)
outputs = model(videos)
_, preds = torch.max(outputs, 1)
val_correct += (preds == labels).sum().item()
val_total += labels.size(0)
val_acc = 100 * val_correct / val_total
print(f"π― Validation Acc: {val_acc:.2f}%")
# β
Save best model
if val_acc > best_acc:
best_acc = val_acc
torch.save(model.state_dict(), "best_model.pth")
print("π Best model saved!")
# =========================
# TEST
# =========================
model.eval()
test_correct, test_total = 0, 0
with torch.no_grad():
for videos, labels in test_loader:
videos, labels = videos.to(DEVICE), labels.to(DEVICE)
outputs = model(videos)
_, preds = torch.max(outputs, 1)
test_correct += (preds == labels).sum().item()
test_total += labels.size(0)
print(f"\nπ Final Test Accuracy: {100*test_correct/test_total:.2f}%")
torch.save(model.state_dict(), "final_model.pth")
print("β
Final model saved as final_model.pth")
# =========================
if __name__ == "__main__":
main() |