-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_v3.py
332 lines (260 loc) · 10.1 KB
/
train_v3.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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import os
import random
import re
import zipfile
from pathlib import Path
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader, Subset, ConcatDataset, random_split
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
from JigsawNet import JigsawNet
from sklearn.model_selection import KFold
class JigsawDataset(Dataset):
def __init__(self, data, labels):
self.data = data
self.labels = labels
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
puzzle = self.data[idx]
label = self.labels[idx]
return puzzle, label
# save checkpoint function
def checkpoint_save(model, save_path, epoch):
filename = "checkpoint-{:03d}.pth".format(epoch)
f = os.path.join(save_path, filename)
torch.save(model.state_dict(), f)
print("saved checkpoint:", f, flush=True)
def checkpoint_delete(save_path, epoch):
filename = "checkpoint-{:03d}.pth".format(epoch)
f = os.path.join(save_path, filename)
os.remove(f)
# save checkpoint function
def checkpoint_load(model, save_path, epoch, n_classes=0, model_ver=1):
filename = "checkpoint-{:03d}.pth".format(epoch)
f = os.path.join(save_path, filename)
model.load_state_dict(torch.load(f))
print("loaded checkpoint:", f, flush=True)
def load_training_data():
# Load the labels
labels = np.loadtxt(f"data/train/label_train.txt")
labels = torch.from_numpy(labels).long()
filename = "data/preprocessed_train.npy"
path = Path(filename)
data = None
if path.is_file():
preprocessed_data = np.load(filename)
# Convert the NumPy array to PyTorch tensors
data = torch.from_numpy(preprocessed_data).float()
print(f"loaded training data from: {filename}")
else:
fold = 0
labels_one_fold = labels
while True:
filename = f"data/preprocessed_train_{fold}.npy"
path = Path(filename)
if path.is_file():
preprocessed_data = np.load(filename)
# Convert the NumPy array to PyTorch tensors
temp = torch.from_numpy(preprocessed_data).float()
if fold > 0:
data = ConcatDataset([data, temp])
labels = ConcatDataset([labels, labels_one_fold])
else:
data = temp
print(f"loaded training data from: {filename}")
fold += 1
else:
break
return data, labels
def get_k_fold_training_datasets(kfold, dataset, fold):
print(f"get_k_fold_training_datasets: fold={fold}")
for idx, (train_ids, val_ids) in enumerate(kfold.split(dataset)):
if idx == fold:
train_subset = Subset(dataset, train_ids)
val_subset = Subset(dataset, val_ids)
return train_subset, val_subset
def train_model(
model,
train_loader,
val_loader,
optimizer,
scheduler,
criterion,
num_epochs,
load_checkpoint=False,
):
save_path = os.path.join(os.getcwd(), "data", "checkpoints/")
os.makedirs(save_path, exist_ok=True)
for _, _, files in os.walk(save_path):
for filename in files:
checkpoint = int(re.split("[-.]", filename)[-2])
if load_checkpoint:
checkpoint_load(model, save_path, checkpoint)
checkpoint_delete(save_path, checkpoint)
highest_accuracy = 0
best_epoch = -1
for epoch in range(num_epochs):
model.train()
total_loss = 0.0
correct_predictions = 0
total_predictions = 0
learning_rate = optimizer.state_dict()["param_groups"][0]["lr"]
print(f"Epoch {epoch + 1}, Learning rate: {learning_rate:.10f}", flush=True)
for puzzle, label in train_loader:
puzzle, label = puzzle.to(device), label.to(device)
optimizer.zero_grad()
outputs = model(puzzle)
loss = criterion(outputs, label)
loss.backward()
optimizer.step()
total_loss += loss.item()
# Calculate accuracy for this batch
_, predicted = torch.max(outputs, 1)
total_predictions += label.size(0)
correct_predictions += (predicted == label).sum().item()
# scheduler.step()
avg_loss = total_loss / len(train_loader)
accuracy = correct_predictions / total_predictions
print(
f"Epoch {epoch + 1}, Training Loss: {avg_loss:.4f}, Training Accuracy: {accuracy * 100:.2f}%",
flush=True,
)
# Validation for this epoch
model.eval()
with torch.no_grad():
correct_predictions = 0
total_predictions = 0
val_loss = []
for inputs, targets in val_loader:
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
loss = criterion(outputs, targets)
batch_loss_value = loss.item()
val_loss.append(batch_loss_value)
# Calculate accuracy for this batch
_, predicted = torch.max(outputs, 1)
total_predictions += targets.size(0)
correct_predictions += (predicted == targets).sum().item()
# Print statistics
loss_value = np.mean(val_loss)
accuracy = correct_predictions / total_predictions
print(
f"Epoch {epoch + 1}, Validation Loss: {loss_value:.4f}, Validation Accuracy: {accuracy * 100:.2f}%",
flush=True,
)
if accuracy > highest_accuracy:
if best_epoch >= 0:
checkpoint_delete(save_path, best_epoch)
highest_accuracy = accuracy
best_epoch = epoch
checkpoint_save(model, save_path, epoch)
print(
f"Best epoch {best_epoch + 1}, Highest Validation Accuracy: {highest_accuracy * 100:.2f}%",
flush=True,
)
class JigsawValidationDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
puzzle = self.data[idx]
return puzzle
def evaluate_model(model, data_loader):
save_path = os.path.join(os.getcwd(), "data", "checkpoints/")
for _, _, files in os.walk(save_path):
filename = files[0]
checkpoint = int(re.split("[-.]", filename)[-2])
checkpoint_load(model, save_path, checkpoint)
model.eval()
all_predictions = [] # To store translated predictions
with torch.no_grad():
for puzzle in data_loader:
puzzle = puzzle.to(device)
output = model(puzzle)
_, predicted = torch.max(
output, 1
) # Get the index of the max log-probability
all_predictions.extend(predicted.cpu().detach().numpy())
all_predictions = np.array(all_predictions)
all_predictions = all_predictions.astype(int)
# Save the predicted values to a text file
filename = "data/validation.txt"
np.savetxt(filename, all_predictions, fmt="%d")
# compress the results folder
zip_filename = "data/result.zip"
path = Path(zip_filename)
if path.is_file():
os.remove(zip_filename)
with zipfile.ZipFile(zip_filename, "w") as zipf:
zipf.write(filename, arcname="validation.txt")
print(f"results saved to: {zip_filename}")
RANDOM_SEED = 193
# RANDOM_SEED = 194
# RANDOM_SEED = 1940
# initialising seed for reproducibility
torch.manual_seed(RANDOM_SEED)
torch.cuda.manual_seed(RANDOM_SEED)
seeded_generator = torch.Generator().manual_seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
random.seed(RANDOM_SEED)
torch.backends.cudnn.deterministic = True
# Check if GPU is available
if torch.cuda.is_available():
device = torch.device("cuda") # Use GPU
else:
device = torch.device("cpu") # Use CPU
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--epochs", type=int, help="Number of epochs", default=20)
parser.add_argument("-b", "--batch", type=int, help="Batch size", default=32)
# Parse the arguments
args = parser.parse_args()
print(device)
num_classes = 50
batch_size = args.batch
num_epochs = args.epochs
print("epochs: ", num_epochs, "batch", batch_size)
# Create the model
# model = JigsawModel(n_classes=num_classes).to(device)
model = JigsawNet(n_classes=num_classes).to(device)
if num_epochs > 0:
data, labels = load_training_data()
kfold = KFold(n_splits=5, shuffle=True)
# Define the dataset and dataloader
dataset = JigsawDataset(data, labels)
print(f"dataset len: {len(dataset)}")
for fold in range(5):
train_set, val_set = get_k_fold_training_datasets(kfold, dataset, fold)
print(f"Fold: {fold + 1}")
print(f"\ttrain_set len: {len(train_set)}")
print(f"\tval_set len: {len(val_set)}")
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=False)
val_loader = DataLoader(val_set, batch_size=batch_size, shuffle=False)
# Define the optimizer and loss function
optimizer = optim.AdamW(model.parameters(), lr=0.001, weight_decay=1e-3)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=18, gamma=0.5)
criterion = nn.CrossEntropyLoss()
# Train the model
train_model(
model,
train_loader,
val_loader,
optimizer,
scheduler,
criterion,
num_epochs,
load_checkpoint=fold > 0,
)
validation_data = np.load(f"data/preprocessed_validation.npy")
validation_data = torch.from_numpy(validation_data).float()
validation_dataset = JigsawValidationDataset(validation_data)
validation_loader = DataLoader(
validation_dataset, batch_size=batch_size, shuffle=False
)
# Evaluate the model and save the results to a text file
evaluate_model(model, validation_loader)