-
Notifications
You must be signed in to change notification settings - Fork 1
/
pretrain_NVGesture.py
197 lines (159 loc) · 7.03 KB
/
pretrain_NVGesture.py
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
import torch
import torch.nn as nn
from torchvision.transforms import (
Compose,
Lambda,
RandomHorizontalFlip
)
from torchvision.transforms._transforms_video import (
CenterCropVideo,
RandomCropVideo
)
from pytorchvideo.transforms import (
UniformTemporalSubsample,
Normalize,
RandomShortSideScale
)
from torch.utils.data import DataLoader, random_split
from dataset.NVGesture.loader import NVGestureColorDataset
from models.c3d import C3D
from models.c3d_v2 import FineTunedC3D as C3Dv2
import numpy as np
from tqdm import tqdm
def train(model, optimizer, criterion, train_loader, val_loader, val_step, num_epochs, device, pbar=None):
best_val_accuracy = 0
############### Training ##################
for epoch in range(num_epochs):
model.train()
epoch_loss = []
corrects = 0
totals = 0
if pbar:
pbar.set_description("[Epoch {}]".format(epoch))
pbar.reset()
for i, data in enumerate(train_loader):
videos, labels = data
videos = videos.float()
videos = videos.to(device) # Send inputs to CUDA
optimizer.zero_grad()
logits = model(videos)
labels = labels.to(device)
loss = criterion(logits, labels)
loss.backward()
epoch_loss.append(loss.item())
optimizer.step()
if pbar:
pbar.update(videos.shape[0])
y_preds = torch.argmax(torch.softmax(logits, dim=1), dim=1)
corrects += (y_preds == labels).sum().item()
totals += y_preds.shape[0]
torch.save(model.state_dict(), 'models/saves/c3d_current.h5')
# Validate the model every <validation_step> epochs of training
print("[Epoch {}] Avg Loss: {}".format(epoch, np.array(epoch_loss).mean()))
print("[Epoch {}] Train Accuracy {:.2f}%".format(epoch, 100 * corrects / totals))
if epoch % val_step == 0:
val_accuracy = test(loader=val_loader, model=model, device=device, epoch=epoch)
if val_accuracy > best_val_accuracy:
# Save the best model based on validation accuracy metric
torch.save(model.state_dict(), 'models/saves/c3d_best.h5')
best_val_accuracy = val_accuracy
def test(loader, model, device, epoch=None):
totals = 0
corrects = 0
y_pred = []
y_true = []
with torch.no_grad():
model.eval()
for i, data in enumerate(loader):
videos, labels = data
videos = videos.float()
videos = videos.to(device)
logits = model(videos)
y_true.append(labels)
y_preds = torch.argmax(torch.softmax(logits, dim=1), dim=1)
y_preds = y_preds.detach().cpu()
y_pred.append(y_preds)
corrects += (y_preds == labels).sum().item()
totals += y_preds.shape[0]
y_true = torch.cat(y_true, dim=0)
y_pred = torch.cat(y_pred, dim=0)
test_accuracy = 100 * corrects / totals
if epoch is not None:
print('[Epoch {}] Validation Accuracy: {:.2f}%'.format(epoch, test_accuracy))
else:
print('Test Accuracy: {:.2f}%'.format(test_accuracy))
return test_accuracy
if __name__ == '__main__':
torch.manual_seed(42) # Reproducibility Purposes
# Define the crop size
crop_size = (112, 112) # Size of the crop
################ Details for Data Augmentation ###################
# random spatial rotation (±15◦) and scaling (±20%), temporal scaling (±20%), and jittering (±3 frames)
# Define the data augmentation transforms
spatial_rotation_angle = 15 # Maximum spatial rotation angle in degrees
spatial_scale = 0.2 # Maximum spatial scaling factor
temporal_scale = 0.2 # Maximum temporal scaling factor
frame_jitter = 3 # Maximum number of frames to jitter
n_frames = 16 # Temporal stride of 80//16 = 5
mean_vector = [0.45, 0.45, 0.45] # Compute these values over NVGesture dataset
std_vector = [0.225, 0.225, 0.225] # Same as above
train_transforms = Compose([
UniformTemporalSubsample(n_frames),
Lambda(lambda x: x/255.0),
Normalize(mean_vector, std_vector),
RandomCropVideo(crop_size)
])
test_transforms = Compose([
UniformTemporalSubsample(n_frames),
Lambda(lambda x: x/255.0),
Normalize(mean_vector, std_vector),
CenterCropVideo(crop_size)
])
batch_size=32
num_epochs=100
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("Running on device {}".format(device))
train_dataset = NVGestureColorDataset(annotations_file='dataset/NVGesture/nvgesture_train_correct_cvpr2016.lst',
path_prefix='dataset/NVGesture',
transforms=train_transforms,
image_height=120,
image_width=160)
test_dataset = NVGestureColorDataset(annotations_file='dataset/NVGesture/nvgesture_test_correct_cvpr2016.lst',
path_prefix='dataset/NVGesture',
transforms=test_transforms,
image_height=120,
image_width=160)
train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# Testing if it works correctly
train_features, train_labels = next(iter(train_dataloader))
print(f"Feature batch shape: {train_features.size()}")
print(f"Labels batch shape: {train_labels.size()}")
print('Size of Train Set: {}'.format(len(train_dataset)))
print('Size of Test Set: {}'.format(len(test_dataset)))
video, label = train_dataset[0]
C, T, H, W = video.shape
print(f"Video shape = {(C, T, H, W)}")
# model = C3D(channels=C, length=T, height=H, width=W, tempdepth=3, outputs=25)
model = C3Dv2(pretrained_model_path='./models/pretrained/c3d.pickle', outputs=25)
print(f"Total parameters: {sum(p.numel() for p in model.parameters())}")
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print("Trainable parameters:", trainable_params)
# optimizer = torch.optim.SGD(list(model.parameters()), lr=3e-3, momentum=0.9, weight_decay=5e-3)
optimizer = torch.optim.AdamW(list(model.parameters()), lr=1e-2)
criterion = nn.CrossEntropyLoss()
model.to(device)
step = 1
pbar = tqdm(total=len(train_dataset))
train(model=model,
optimizer=optimizer,
criterion=criterion,
train_loader=train_dataloader,
val_loader=test_dataloader,
val_step=5,
num_epochs=num_epochs,
device=device,
pbar=pbar)
test(loader=test_dataloader,
model=model,
device=device)