-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.py
243 lines (220 loc) · 7.04 KB
/
main.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
import argparse
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torchvision import datasets
from tqdm import tqdm
from model_factory import ModelFactory
def opts() -> argparse.ArgumentParser:
"""Option Handling Function."""
parser = argparse.ArgumentParser(description="RecVis A3 training script")
parser.add_argument(
"--data",
type=str,
default="data_sketches",
metavar="D",
help="folder where data is located. train_images/ and val_images/ need to be found in the folder",
)
parser.add_argument(
"--model_name",
type=str,
default="basic_cnn",
metavar="MOD",
help="Name of the model for model and transform instantiation",
)
parser.add_argument(
"--batch-size",
type=int,
default=64,
metavar="B",
help="input batch size for training (default: 64)",
)
parser.add_argument(
"--epochs",
type=int,
default=10,
metavar="N",
help="number of epochs to train (default: 10)",
)
parser.add_argument(
"--lr",
type=float,
default=0.1,
metavar="LR",
help="learning rate (default: 0.01)",
)
parser.add_argument(
"--momentum",
type=float,
default=0.5,
metavar="M",
help="SGD momentum (default: 0.5)",
)
parser.add_argument(
"--seed", type=int, default=1, metavar="S", help="random seed (default: 1)"
)
parser.add_argument(
"--log-interval",
type=int,
default=10,
metavar="N",
help="how many batches to wait before logging training status",
)
parser.add_argument(
"--experiment",
type=str,
default="experiment",
metavar="E",
help="folder where experiment outputs are located.",
)
parser.add_argument(
"--num_workers",
type=int,
default=10,
metavar="NW",
help="number of workers for data loading",
)
args = parser.parse_args()
return args
def train(
model: nn.Module,
optimizer: torch.optim.Optimizer,
train_loader: torch.utils.data.DataLoader,
use_cuda: bool,
epoch: int,
args: argparse.ArgumentParser,
) -> None:
"""Default Training Loop.
Args:
model (nn.Module): Model to train
optimizer (torch.optimizer): Optimizer to use
train_loader (torch.utils.data.DataLoader): Training data loader
use_cuda (bool): Whether to use cuda or not
epoch (int): Current epoch
args (argparse.ArgumentParser): Arguments parsed from command line
"""
model.train()
correct = 0
for batch_idx, (data, target) in enumerate(train_loader):
if use_cuda:
data, target = data.cuda(), target.cuda()
optimizer.zero_grad()
output = model(data)
criterion = torch.nn.CrossEntropyLoss(reduction="mean")
loss = criterion(output, target)
loss.backward()
optimizer.step()
pred = output.data.max(1, keepdim=True)[1]
correct += pred.eq(target.data.view_as(pred)).cpu().sum()
if batch_idx % args.log_interval == 0:
print(
"Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format(
epoch,
batch_idx * len(data),
len(train_loader.dataset),
100.0 * batch_idx / len(train_loader),
loss.data.item(),
)
)
print(
"\nTrain set: Accuracy: {}/{} ({:.0f}%)\n".format(
correct,
len(train_loader.dataset),
100.0 * correct / len(train_loader.dataset),
)
)
def validation(
model: nn.Module,
val_loader: torch.utils.data.DataLoader,
use_cuda: bool,
) -> float:
"""Default Validation Loop.
Args:
model (nn.Module): Model to train
val_loader (torch.utils.data.DataLoader): Validation data loader
use_cuda (bool): Whether to use cuda or not
Returns:
float: Validation loss
"""
model.eval()
validation_loss = 0
correct = 0
for data, target in val_loader:
if use_cuda:
data, target = data.cuda(), target.cuda()
output = model(data)
# sum up batch loss
criterion = torch.nn.CrossEntropyLoss(reduction="mean")
validation_loss += criterion(output, target).data.item()
# get the index of the max log-probability
pred = output.data.max(1, keepdim=True)[1]
correct += pred.eq(target.data.view_as(pred)).cpu().sum()
validation_loss /= len(val_loader.dataset)
print(
"\nValidation set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)".format(
validation_loss,
correct,
len(val_loader.dataset),
100.0 * correct / len(val_loader.dataset),
)
)
return validation_loss
def main():
"""Default Main Function."""
# options
args = opts()
# Check if cuda is available
use_cuda = torch.cuda.is_available()
# Set the seed (for reproducibility)
torch.manual_seed(args.seed)
# Create experiment folder
if not os.path.isdir(args.experiment):
os.makedirs(args.experiment)
# load model and transform
model, data_transforms = ModelFactory(args.model_name).get_all()
if use_cuda:
print("Using GPU")
model.cuda()
else:
print("Using CPU")
# Data initialization and loading
train_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(args.data + "/train_images", transform=data_transforms),
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers,
)
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(args.data + "/val_images", transform=data_transforms),
batch_size=args.batch_size,
shuffle=False,
num_workers=args.num_workers,
)
# Setup optimizer
optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)
# Loop over the epochs
best_val_loss = 1e8
for epoch in range(1, args.epochs + 1):
# training loop
train(model, optimizer, train_loader, use_cuda, epoch, args)
# validation loop
val_loss = validation(model, val_loader, use_cuda)
if val_loss < best_val_loss:
# save the best model for validation
best_val_loss = val_loss
best_model_file = args.experiment + "/model_best.pth"
torch.save(model.state_dict(), best_model_file)
# also save the model every epoch
model_file = args.experiment + "/model_" + str(epoch) + ".pth"
torch.save(model.state_dict(), model_file)
print(
"Saved model to "
+ model_file
+ f". You can run `python evaluate.py --model_name {args.model_name} --model "
+ best_model_file
+ "` to generate the Kaggle formatted csv file\n"
)
if __name__ == "__main__":
main()