-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_modify.py
514 lines (409 loc) · 17.6 KB
/
train_modify.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import torch
import sys, os
import argparse
import numpy as np
import seaborn as sns
import torchvision
from torchvision import transforms, datasets
import torch.optim as optim
from torch.optim import lr_scheduler
from torch import nn
import time
import copy
import pickle
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.metrics import roc_auc_score, roc_curve, auc, confusion_matrix, ConfusionMatrixDisplay, classification_report
sys.path.insert(1,'helpers')
sys.path.insert(1,'model')
sys.path.insert(1,'weight')
from augmentation import Aug
from xmodel import XMT
from loader import session
import optparse
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#Default
cession='g' # GPU runtime
epoch = 1
dir_path = ""
batch_size = 32
lr=0.0001
weight_decay=0.0000001
parser = optparse.OptionParser("Train XMT model.")
parser.add_option("-e", "--epoch", type=int, dest='epoch', help='Number of epochs used for training the X model.')
parser.add_option("-v", "--version", dest='version', help='Version 0.1.')
parser.add_option("-s", "--cession", type="string",dest='session', help='Training session. Use g for GPU, t for TPU.')
parser.add_option("-d", "--dir", dest='dir', help='Training data path.')
parser.add_option("-b", "--batch", type=int, dest='batch', help='Batch size.')
parser.add_option("-l", "--rate", type=float, dest='rate', help='Learning rate.')
parser.add_option("-w", "--decay", type=float, dest='decay', help='Weight decay.')
parser.add_option("-p", "--plot", action="store_true", dest='plot', help='Plot training and validation metrics.')
(options,args) = parser.parse_args()
plot_metrics = False
if options.session:
cession = options.session
if options.dir==None:
print (parser.usage)
exit(0)
else:
dir_path = options.dir
if options.batch:
batch_size = int(options.batch)
if options.epoch:
epoch = int(options.epoch)
if options.rate:
lr = float(options.rate)
if options.decay:
weight_decay = float(options.decay)
if options.plot:
plot_metrics = True
if cession=='t':
print('USING TPU.')
device = xm.xla_device()
batch_size, dataloaders, dataset_sizes = session(cession, dir_path, batch_size)
#X model definition
model = XMT(image_size=224, patch_size=7, num_classes=2, channels=1024, dim=1024, depth=6, heads=8, mlp_dim=2048, gru_hidden_size=1024)
model.to(device)
optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)
criterion = torch.nn.CrossEntropyLoss()
criterion.to(device)
num_epochs = epoch
min_val_loss=10000
scheduler = lr_scheduler.StepLR(optimizer, step_size=15, gamma=0.1)
def save_metrics_to_file(metrics, filename):
# Specify the writeable directory path, adjust as per your environment
writeable_dir = '/kaggle/working/'
filepath = writeable_dir + filename
with open(filepath, "a") as file:
for key, values in metrics.items():
file.write(f"{key}: {values[-1]}\n")
file.write("\n")
def train_tpu(model, criterion, optimizer, scheduler, num_epochs, min_val_loss, plot_metrics):
model_path = 'weight/xmodel_deepfake_sample_1.pth'
if os.path.exists(model_path):
print("Loading saved model...")
checkpoint = torch.load(model_path)
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
start_epoch = checkpoint['epoch']
min_val_loss = checkpoint['min_loss']
else:
print("Train from begining...")
start_epoch = 0
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
min_loss = min_val_loss
train_loss = []
train_accu = []
val_loss = []
val_accu = []
epoch_loss = None
total_epochs = start_epoch + num_epochs
for epoch in range(start_epoch, total_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1))
print('-' * 10)
for phase in ['train', 'val']:
if phase == 'train':
model.train()
else:
model.eval()
running_loss = 0.0
running_corrects = 0
phase_idx=0
epoch_loss = running_loss / dataset_sizes[phase]
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
if phase == 'train':
loss.backward()
xm.optimizer_step(optimizer, barrier=True)
xm.mark_step()
if phase_idx%100==0:
print(phase,' loss:',phase_idx,':', loss.item())
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, phase_idx * batch_size, dataset_sizes[phase],\
100. * phase_idx*batch_size / dataset_sizes[phase], loss.item()))
phase_idx+=1
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
if phase == 'train':
scheduler.step()
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
if phase == 'train':
train_loss.append(epoch_loss)
train_accu.append(epoch_acc)
else:
val_loss.append(epoch_loss)
val_accu.append(epoch_acc)
if phase == 'val':
if epoch_acc > best_acc:
best_acc = epoch_acc.item() # Update the best accuracy
best_model_wts = copy.deepcopy(model.state_dict())
print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))
if phase == 'val' and epoch_loss < min_loss:
print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(epoch_loss, min_loss))
min_loss = epoch_loss
best_model_wts = copy.deepcopy(model.state_dict())
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))
print('Best val Acc: {:4f}'.format(best_acc))
model.load_state_dict(best_model_wts)
with open('weight/xmodel_deepfake_sample_1.pkl', 'wb') as f:
pickle.dump([train_loss, train_accu, val_loss, val_accu], f)
if epoch_loss is not None:
state = {'epoch': num_epochs+1,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
'min_loss': epoch_loss}
torch.save(state, 'weight/xmodel_deepfake_sample_1.pth')
if plot_metrics == True:
plt.figure(figsize=(10, 5))
plt.title("Training and Validation Loss")
plt.plot(val_loss, label="val")
plt.plot(train_loss, label="train")
plt.xlabel("Iterations")
plt.ylabel("Loss")
plt.legend()
plt.savefig('/kaggle/working/training_validation_loss.png')
plt.close()
plt.figure(figsize=(10, 5))
plt.title("Training and Validation Accuracy")
plt.plot([acc.cpu().numpy() for acc in val_accu], label="val")
plt.plot([acc.cpu().numpy() for acc in train_accu], label="train")
plt.xlabel("Iterations")
plt.ylabel("Accuracy")
plt.legend()
plt.savefig('/kaggle/working/training_validation_accuracy.png')
plt.close()
return train_loss,train_accu,val_loss,val_accu, min_loss
def train_gpu(model, criterion, optimizer, scheduler, num_epochs, min_val_loss, plot_metrics):
# Initialize lists to keep track of metrics
train_loss = []
train_accu = []
val_loss = []
val_accu = []
test_loss = [] # If testing after each epoch
test_acc = [] # If testing after each epoch
# For saving metrics to file
metrics = {
'train_loss': train_loss,
'train_acc': train_accu,
'val_loss': val_loss,
'val_acc': val_accu,
'test_loss': test_loss,
'test_acc': test_acc
}
# Load existing model if it exists
model_path = '/kaggle/working/xmodel_deepfake_sample_1.pth'
if os.path.exists(model_path):
print("Loading saved model...")
checkpoint = torch.load(model_path)
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
start_epoch = checkpoint['epoch']
min_val_loss = checkpoint['min_loss']
else:
start_epoch = 0
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
min_loss = min_val_loss
epoch_loss = None # Initialize epoch_loss outside of the loop
total_epochs = start_epoch + num_epochs
for epoch in range(start_epoch, total_epochs):
print('Epoch {}/{}'.format(epoch, total_epochs - 1))
print('-' * 10)
for phase in ['train', 'val']:
if phase == 'train':
model.train()
else:
model.eval()
running_loss = 0.0
running_corrects = 0
phase_idx = 0
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
if phase == 'train':
loss.backward()
optimizer.step()
if phase_idx%100==0:
print(phase,' loss:',phase_idx,':', loss.item())
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, phase_idx * batch_size, dataset_sizes[phase], \
100. * phase_idx*batch_size / dataset_sizes[phase], loss.item()))
phase_idx+=1
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
if phase == 'train':
train_loss.append(epoch_loss)
train_accu.append(epoch_acc)
else:
val_loss.append(epoch_loss)
val_accu.append(epoch_acc)
if epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))
if phase == 'val' and epoch_loss < min_loss:
min_loss = epoch_loss
best_model_wts = copy.deepcopy(model.state_dict())
print('Validation loss decreased ({:.6f}). Saving model ...'.format(min_loss))
# Optionally perform testing after each epoch
test_loss_value, test_acc_value = test(model, dataloaders, dataset_sizes, device, criterion)
test_loss.append(test_loss_value)
test_acc.append(test_acc_value)
# Save metrics to file after each epoch
save_metrics_to_file(metrics, 'training_metrics.txt')
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))
print('Best val Acc: {:4f}'.format(best_acc))
model.load_state_dict(best_model_wts)
with open('/kaggle/working/xmodel_deepfake_sample_1.pkl', 'wb') as f:
pickle.dump([train_loss, train_accu, val_loss, val_accu, test_loss, test_acc], f)
if epoch_loss is not None: # Now it is safe to check epoch_loss
state = {'epoch': num_epochs+1,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
'min_loss': min_loss}
torch.save(state, '/kaggle/working/xmodel_deepfake_sample_1.pth')
auc_score = calculate_auc(model, dataloaders, dataset_sizes)
print('AUC:', auc_score)
cm = calculate_confusion_matrix(model, dataloaders, dataset_sizes)
print('confusion_matrix', cm)
if plot_metrics:
# Training and Validation Loss
plt.figure(figsize=(10, 5))
plt.title("Training and Validation Loss")
plt.plot(train_loss, label="Train Loss")
plt.plot(val_loss, label="Validation Loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.savefig('/kaggle/working/training_validation_loss.png')
plt.close()
# Training and Validation Accuracy
plt.figure(figsize=(10, 5))
plt.title("Training and Validation Accuracy")
plt.plot([acc.cpu().numpy() for acc in train_accu], label="Train Accuracy")
plt.plot([acc.cpu().numpy() for acc in val_accu], label="Validation Accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.savefig('/kaggle/working/training_validation_accuracy.png')
plt.close()
# Test Loss
plt.figure(figsize=(10, 5))
plt.title("Test Loss")
plt.plot(test_loss, label="Test Loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.savefig('/kaggle/working/test_loss.png')
plt.close()
# Test Accuracy
plt.figure(figsize=(10, 5))
plt.title("Test Accuracy")
plt.plot([acc.cpu().numpy() for acc in test_acc], label="Test Accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.savefig('/kaggle/working/test_accuracy.png')
plt.close()
return train_loss, train_accu, val_loss, val_accu, min_loss
def calculate_auc(model, dataloaders, dataset_sizes):
model.eval()
all_labels = []
all_preds = []
for inputs, labels in dataloaders['test']:
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
_, predictions = torch.max(outputs, 1)
outputs = outputs.softmax(dim=1)
all_labels.extend(labels.tolist())
all_preds.extend(outputs[:, 1].tolist())
fpr, tpr, thresholds = roc_curve(all_labels, all_preds)
roc_auc = auc(fpr, tpr)
plt.figure()
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic')
plt.legend(loc="lower right")
plt.savefig('/kaggle/working/roc_curve.png')
plt.close()
return roc_auc
def calculate_confusion_matrix(model, dataloaders, dataset_sizes):
model.eval()
all_labels = []
all_preds = []
for inputs, labels in dataloaders['test']:
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
_, predictions = torch.max(outputs, 1)
all_labels.extend(labels.tolist())
all_preds.extend(predictions.tolist())
cm = confusion_matrix(all_labels, all_preds)
report = classification_report(all_labels, all_preds, output_dict=True, zero_division=0)
f1_score = report['weighted avg']['f1-score']
precision = report['weighted avg']['precision']
recall = report['weighted avg']['recall']
print(f"F1 Score: {f1_score:.2f}, Precision: {precision:.2f}, Recall: {recall:.2f}")
group_names = ['True Neg', 'False Pos', 'False Neg', 'True Pos']
group_counts = ["{0:0.0f}".format(value) for value in cm.flatten()]
group_percentages = ["{0:.2%}".format(value) for value in cm.flatten()/np.sum(cm)]
labels = [f"{v1}\n{v2}\n{v3}" for v1, v2, v3 in zip(group_names, group_counts, group_percentages)]
labels = np.asarray(labels).reshape(2,2)
sns.heatmap(cm, annot=labels, fmt='', cmap='Blues')
plt.ylabel('Actual label')
plt.xlabel('Predicted label')
plt.xticks(np.arange(2), ['Fake', 'Real'], size = 16)
plt.yticks(np.arange(2), ['Fake', 'Real'], size = 16)
plt.title('Confusion Matrix')
plt.savefig('/kaggle/working/confusion_matrix.png')
plt.close()
return cm
def test(model, dataloaders, dataset_sizes, device, criterion):
model.eval()
running_loss = 0.0
running_corrects = 0
# Ensure the model is in evaluation mode and calculations are done without tracking gradients
for inputs, labels in dataloaders['test']:
inputs = inputs.to(device)
labels = labels.to(device)
with torch.no_grad():
outputs = model(inputs)
loss = criterion(outputs, labels)
_, preds = torch.max(outputs, 1)
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
total_loss = running_loss / dataset_sizes['test']
total_acc = running_corrects.double() / dataset_sizes['test']
accuracy_percentage = total_acc * 100 # Convert to percentage
print('Test Loss: {:.4f}'.format(total_loss))
print('Test Accuracy: {:.2f}%'.format(accuracy_percentage))
return total_loss, accuracy_percentage
if cession == 't':
train_tpu(model, criterion, optimizer, scheduler, num_epochs, min_val_loss, plot_metrics)
else:
train_gpu(model, criterion, optimizer, scheduler, num_epochs, min_val_loss, plot_metrics)