DIMPU1516 commited on
Commit
343b5d3
Β·
verified Β·
1 Parent(s): f6a38ab

Upload train.py

Browse files
Files changed (1) hide show
  1. train.py +258 -0
train.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import torch
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+ from torch.utils.data import Dataset, DataLoader
8
+ from torchvision import transforms
9
+ from pytorchvideo.models.resnet import create_resnet
10
+
11
+ import torch.nn as nn
12
+ import torch.optim as optim
13
+ from tqdm import tqdm
14
+
15
+ # =========================
16
+ # CONFIG
17
+ # =========================
18
+ NUM_FRAMES = 16
19
+ IMG_SIZE = 112
20
+ BATCH_SIZE = 8
21
+ EPOCHS = 20
22
+ LR = 5e-5
23
+
24
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
25
+ print("πŸš€ Using device:", DEVICE)
26
+
27
+ # =========================
28
+ # DATASET
29
+ # =========================
30
+ class AirLettersDataset(Dataset):
31
+ def __init__(self, csv_path, video_dir):
32
+ self.df = pd.read_csv(csv_path)
33
+ self.df.columns = self.df.columns.str.strip()
34
+ self.video_dir = video_dir
35
+
36
+ self.transform = transforms.Compose([
37
+ transforms.ToPILImage(),
38
+ transforms.Resize((IMG_SIZE, IMG_SIZE)), # βœ… no cropping issues
39
+ transforms.RandomHorizontalFlip(p=0.3),
40
+ transforms.RandomRotation(10),
41
+ transforms.ToTensor(),
42
+ transforms.Normalize([0.45]*3, [0.225]*3)
43
+ ])
44
+
45
+ def __len__(self):
46
+ return len(self.df)
47
+
48
+ def get_label(self, label):
49
+ label = label.lower().strip()
50
+
51
+ try:
52
+ if "letter" in label:
53
+ char = label.split("letter")[1].strip()[0]
54
+ return ord(char.upper()) - ord('A')
55
+
56
+ elif "digit" in label:
57
+ digit = label.split("digit")[1].strip()[0]
58
+ return 26 + int(digit)
59
+
60
+ elif "doing nothing" in label:
61
+ return 36
62
+
63
+ else:
64
+ return 37
65
+ except:
66
+ return 37
67
+
68
+ def load_video(self, path):
69
+ cap = cv2.VideoCapture(path)
70
+
71
+ if not cap.isOpened():
72
+ return None
73
+
74
+ total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
75
+ if total == 0:
76
+ cap.release()
77
+ return None
78
+
79
+ indices = np.linspace(0, total - 1, NUM_FRAMES).astype(int)
80
+ frames = []
81
+
82
+ for idx in indices:
83
+ cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
84
+ ret, frame = cap.read()
85
+
86
+ if ret and frame is not None:
87
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
88
+ frames.append(self.transform(frame))
89
+
90
+ cap.release()
91
+
92
+ if len(frames) == 0:
93
+ return None
94
+
95
+ while len(frames) < NUM_FRAMES:
96
+ frames.append(frames[-1])
97
+
98
+ return torch.stack(frames).permute(1, 0, 2, 3)
99
+
100
+ def __getitem__(self, idx):
101
+ for _ in range(5):
102
+ row = self.df.iloc[idx]
103
+ video_path = os.path.join(self.video_dir, row['filename'])
104
+
105
+ video = self.load_video(video_path)
106
+
107
+ if video is not None:
108
+ label = self.get_label(row['label'])
109
+ return video, label
110
+
111
+ idx = (idx + 1) % len(self.df)
112
+
113
+ raise RuntimeError("Too many bad videos")
114
+
115
+
116
+ # =========================
117
+ # MAIN
118
+ # =========================
119
+ def main():
120
+
121
+ train_csv = "train.csv"
122
+ val_csv = "val.csv"
123
+ test_csv = "test.csv"
124
+ video_dir = "videos"
125
+
126
+ train_set = AirLettersDataset(train_csv, video_dir)
127
+ val_set = AirLettersDataset(val_csv, video_dir)
128
+ test_set = AirLettersDataset(test_csv, video_dir)
129
+
130
+ train_loader = DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=4, pin_memory=True)
131
+ val_loader = DataLoader(val_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, pin_memory=True)
132
+ test_loader = DataLoader(test_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, pin_memory=True)
133
+
134
+ # =========================
135
+ # MODEL
136
+ # =========================
137
+ model = create_resnet(
138
+ input_channel=3,
139
+ model_depth=101,
140
+ model_num_class=38
141
+ ).to(DEVICE)
142
+
143
+ # =========================
144
+ # LOAD PRETRAINED
145
+ # =========================
146
+ if os.path.exists("resnext200_airletters.pth"):
147
+ print("πŸ“¦ Loading pretrained weights...")
148
+
149
+ state_dict = torch.load("resnext200_airletters.pth", map_location=DEVICE)
150
+ model_dict = model.state_dict()
151
+
152
+ filtered_dict = {k: v for k, v in state_dict.items()
153
+ if k in model_dict and model_dict[k].shape == v.shape}
154
+
155
+ model_dict.update(filtered_dict)
156
+ model.load_state_dict(model_dict)
157
+
158
+ print("βœ… Pretrained loaded safely")
159
+
160
+ # =========================
161
+ # TRAIN SETUP
162
+ # =========================
163
+ criterion = nn.CrossEntropyLoss(label_smoothing=0.1)
164
+ optimizer = optim.Adam(model.parameters(), lr=LR)
165
+
166
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)
167
+ scaler = torch.cuda.amp.GradScaler()
168
+
169
+ best_acc = 0
170
+
171
+ # =========================
172
+ # TRAIN LOOP
173
+ # =========================
174
+ for epoch in range(EPOCHS):
175
+
176
+ model.train()
177
+ correct, total, loss_sum = 0, 0, 0
178
+
179
+ loop = tqdm(train_loader, desc=f"πŸ”₯ Epoch {epoch+1}/{EPOCHS}")
180
+
181
+ for videos, labels in loop:
182
+ videos, labels = videos.to(DEVICE), labels.to(DEVICE)
183
+
184
+ optimizer.zero_grad()
185
+
186
+ # βœ… AMP
187
+ with torch.cuda.amp.autocast():
188
+ outputs = model(videos)
189
+ loss = criterion(outputs, labels)
190
+
191
+ scaler.scale(loss).backward()
192
+ scaler.step(optimizer)
193
+ scaler.update()
194
+
195
+ loss_sum += loss.item()
196
+
197
+ _, preds = torch.max(outputs, 1)
198
+ correct += (preds == labels).sum().item()
199
+ total += labels.size(0)
200
+
201
+ acc = 100 * correct / total
202
+ loop.set_postfix(loss=f"{loss.item():.4f}", acc=f"{acc:.2f}%")
203
+
204
+ scheduler.step()
205
+
206
+ train_acc = 100 * correct / total
207
+ print(f"\nπŸ“ˆ Train Acc: {train_acc:.2f}%")
208
+
209
+ # =========================
210
+ # VALIDATION
211
+ # =========================
212
+ model.eval()
213
+ val_correct, val_total = 0, 0
214
+
215
+ with torch.no_grad():
216
+ for videos, labels in val_loader:
217
+ videos, labels = videos.to(DEVICE), labels.to(DEVICE)
218
+
219
+ outputs = model(videos)
220
+ _, preds = torch.max(outputs, 1)
221
+
222
+ val_correct += (preds == labels).sum().item()
223
+ val_total += labels.size(0)
224
+
225
+ val_acc = 100 * val_correct / val_total
226
+ print(f"🎯 Validation Acc: {val_acc:.2f}%")
227
+
228
+ # βœ… Save best model
229
+ if val_acc > best_acc:
230
+ best_acc = val_acc
231
+ torch.save(model.state_dict(), "best_model.pth")
232
+ print("πŸ† Best model saved!")
233
+
234
+ # =========================
235
+ # TEST
236
+ # =========================
237
+ model.eval()
238
+ test_correct, test_total = 0, 0
239
+
240
+ with torch.no_grad():
241
+ for videos, labels in test_loader:
242
+ videos, labels = videos.to(DEVICE), labels.to(DEVICE)
243
+
244
+ outputs = model(videos)
245
+ _, preds = torch.max(outputs, 1)
246
+
247
+ test_correct += (preds == labels).sum().item()
248
+ test_total += labels.size(0)
249
+
250
+ print(f"\nπŸ† Final Test Accuracy: {100*test_correct/test_total:.2f}%")
251
+
252
+ torch.save(model.state_dict(), "final_model.pth")
253
+ print("βœ… Final model saved as final_model.pth")
254
+
255
+
256
+ # =========================
257
+ if __name__ == "__main__":
258
+ main()