-
Notifications
You must be signed in to change notification settings - Fork 3
/
Training.py
183 lines (142 loc) · 5.62 KB
/
Training.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
# -*- coding: utf-8 -*-
"""notebook-1.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1rEuJRnbZNFTPnh1xdDp6lskX38NuLXUd
"""
from __future__ import print_function, division
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader, random_split
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
from PIL import Image
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from SkinMnistDataset import SkinMnistDataset, data_transforms
from utils import train_model, imshow, evaluate, set_parameter_requires_grad
import os
import time
from datetime import datetime
import os
import copy
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# from google.colab import drive
# drive.mount('/content/drive')
# All the required paths as variables
root_dir = './drive/My Drive/ML_Club/Projects/grad_cam'
dataset_root_dir = os.path.join(root_dir, 'datasets/skin-mnist')
train_csv_file = os.path.join(dataset_root_dir, 'final_train.csv')
val_csv_file = os.path.join(dataset_root_dir, 'final_val.csv')
test_csv_file = os.path.join(dataset_root_dir, 'final_test.csv')
batch_size = 64
shuffle = True
num_classes = 3
num_epochs = 51
run = 5
num_freeze = 30
train_dataset = SkinMnistDataset(
train_csv_file, dataset_root_dir, data_transforms['train'])
val_dataset = SkinMnistDataset(
val_csv_file, dataset_root_dir, data_transforms['test'])
test_dataset = SkinMnistDataset(
test_csv_file, dataset_root_dir, data_transforms['test'])
dataloaders = {
'train': DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=shuffle),
'val': DataLoader(dataset=val_dataset, batch_size=batch_size, shuffle=shuffle),
'test': DataLoader(dataset=test_dataset, batch_size=len(test_dataset))
}
dataset_sizes = {
'train': len(train_dataset),
'val': len(val_dataset),
'test': len(test_dataset)
}
# pop_mean = []
# pop_std0 = []
# for i, data in enumerate(dataloaders['train'], 0):
# # shape (batch_size, 3, height, width)
# numpy_image = data[0].numpy()
# # shape (3,)
# batch_mean = np.mean(numpy_image, axis=(0,2,3))
# batch_std0 = np.std(numpy_image, axis=(0,2,3))
# pop_mean.append(batch_mean)
# pop_std0.append(batch_std0)
# # shape (num_iterations, 3) -> (mean across 0th axis) -> shape (3,)
# pop_mean = np.array(pop_mean).mean(axis=0)
# pop_std0 = np.array(pop_std0).mean(axis=0)
# pop_mean, pop_std0 = [0.6373545 , 0.44605875, 0.46191868], [0.27236816, 0.22500427, 0.24329403]
"""## Initializing Pretrained Model"""
model_ft = models.vgg19_bn(pretrained=True)
set_parameter_requires_grad(model_ft, num_freeze)
num_ftrs = model_ft.classifier[6].in_features
model_ft.fc = nn.Linear(num_ftrs, num_classes)
inputs_size = 224
# model_ft.load_state_dict(torch.load('./drive/My Drive/ML_Club/Projects/grad_cam/models/vgg19/run4/best_model_vgg19.pt'))
# len(list(model_ft.parameters()))
run_path = os.path.join(root_dir, f'models/vgg19/run{run}')
if os.path.isdir(run_path):
print("This run was already completed, please specify a different run if wanna start again")
else:
os.makedirs(run_path)
os.makedirs(os.path.join(run_path, 'checkpoints'))
best_model_path = os.path.join(run_path, 'best_model_vgg19.pt')
checkpoint_dir = os.path.join(run_path, 'checkpoints')
"""## Instatiate Optimizer and criterion and pass in only trainable parameters"""
model_ft = model_ft.to(device)
params_to_update = model_ft.parameters()
print("Parameters to Learn:")
params_to_update = []
for name, param in model_ft.named_parameters():
if param.requires_grad == True:
params_to_update.append(param)
print('\t', name)
print(len(params_to_update))
# optimizer_ft = optim.Adam(params_to_update, lr=0.01)
optimizer_ft = optim.SGD(params_to_update, lr=0.01,
momentum=0.9, nesterov=True)
exp_lr_scheduler = lr_scheduler.ReduceLROnPlateau(
optimizer_ft, mode='min',
factor=0.5, patience=2, verbose=True,
threshold=0.0001, threshold_mode='rel',
cooldown=0, min_lr=0, eps=1e-08
)
criterion = nn.CrossEntropyLoss()
"""# Manage Checkpoints according to the run"""
best_acc = 0.0
start_epoch = 0
hist = {'val_acc': False, 'train_acc': False}
checkpoints = os.listdir(path=checkpoint_dir)
if len(checkpoints):
print(f"Getting the latest checkpoint in run{run}: ")
name = checkpoints[-1]
print(f"Loading Checkpoint file: {name}")
checkpoint_path = os.path.join(checkpoint_dir, name)
checkpoint = torch.load(checkpoint_path)
best_acc = checkpoint['best_acc']
model_ft.load_state_dict(checkpoint['model_state_dict'])
hist = checkpoint['hist']
print(f'{name} loaded successfully')
start_epoch = checkpoint['epoch'] + 1
print(f"{start_epoch} epochs done already")
print(f'traning for {num_epochs - start_epoch} more epochs')
else:
print('training from scratch')
model_ft, hist = train_model(model_ft,
checkpoint_dir,
best_model_path,
dataloaders,
dataset_sizes,
criterion,
optimizer_ft,
scheduler=exp_lr_scheduler,
num_epochs=num_epochs,
start_epoch=start_epoch,
best_acc=best_acc,
hist=hist
)
# model_ft = model_ft.to(device)
# evaluate(model_ft, dataloaders['test'], nn.CrossEntropyLoss())
# print('Test Complete')