This repository has been archived by the owner on Jul 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtraining.py
172 lines (132 loc) · 3.74 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
"""
Implementation of the training procedure of the deep learning models.
"""
###########
# Imports #
###########
import csv
import numpy as np
import os
import torch
import torch.nn as nn
from functools import partial
from torch.optim import Adam, Optimizer
from torch.utils.data import DataLoader
from tqdm import tqdm
from .datasets import ClassDataset, ImageDataset
from .models import DenseNet, SmallConvNet, UNet
from plots.latex import plt
#############
# Functions #
#############
# Utilities
def train_epoch(
loader: DataLoader,
device: torch.device,
model: nn.Module,
criterion: nn.Module,
optimizer: Optimizer
) -> list:
"""
Train a model for one epoch.
"""
losses = []
for inputs, targets in loader:
inputs = inputs.to(device)
targets = targets.to(device)
outputs = model(inputs)
loss = criterion(outputs, targets)
losses.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
return losses
# Main
def train(
outputs_pth: str = 'outputs/',
criterion_id: str = 'mse',
dataset_id: str = 'class',
train_pth: str = 'train.json',
model_id: str = 'densenet161',
augment: bool = False,
edges: bool = False,
batch_size: int = 16,
out_channels: int = 2,
num_epochs: int = 30,
weights_pth: str = 'weights.pth'
):
# Device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
print(f'Device: {device}')
# Output folder
os.makedirs(os.path.dirname(outputs_pth), exist_ok=True)
# Criterion and target dtype
criterions = {
'mse': (nn.MSELoss(), torch.float, 'MSE Loss'),
'nll': (nn.NLLLoss(), torch.long, 'NLL Loss')
}
criterion, dtype, ylabel = criterions.get(criterion_id, 'mse')
# Data set and data loader
print('Loading data set...')
datasets = {
'class': ClassDataset,
'image': ImageDataset
}
trainset = datasets.get(dataset_id, 'class')(
json_pth=train_pth,
augment=augment,
dtype=dtype,
edges=edges
)
loader = DataLoader(
trainset,
shuffle=True,
batch_size=batch_size,
pin_memory=torch.cuda.is_available()
)
# Model
models = {
'densenet121': partial(DenseNet, densenet_id='121'),
'densenet161': partial(DenseNet, densenet_id='161'),
'small': SmallConvNet,
'unet': UNet
}
inpt, _ = trainset[0]
in_channels = inpt.size()[0]
model = models.get(model_id, 'densenet121')(in_channels, out_channels)
model = model.to(device)
model.train()
# Optimizer
optimizer = Adam(model.parameters())
# Statistics file
stats_pth = os.path.join(outputs_pth, 'train.csv')
with open(stats_pth, 'w', newline='') as f:
csv.writer(f).writerow([
'epoch',
'train_loss_mean',
'train_loss_std'
])
# Training
epochs = range(num_epochs)
mean_losses = []
for epoch in tqdm(epochs):
train_losses = train_epoch(loader, device, model, criterion, optimizer)
# Statistics
mean_losses.append(np.mean(train_losses))
with open(stats_pth, 'a', newline='') as f:
csv.writer(f).writerow([
epoch + 1,
np.mean(train_losses),
np.std(train_losses)
])
# Save weights
if epoch == epochs[-1]:
torch.save(model.state_dict(), weights_pth)
# Plot
plt.plot(range(1, num_epochs + 1), mean_losses)
plt.xlabel('Epoch')
plt.ylabel(ylabel)
plt.savefig(os.path.join(outputs_pth, 'train.pdf'))
plt.close()