-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain.py
123 lines (86 loc) · 3.16 KB
/
train.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
import config
import torch
import sys
device = torch.device('cpu')
### Part 1: define model
class Model(torch.nn.Module):
def __init__(self, sensors, chunks):
super().__init__()
self.linear = torch.nn.Sequential(
torch.nn.Linear(sensors, chunks),
torch.nn.ReLU(),
)
def forward(self, input):
output = self.linear(input)
return output
def collate(datas):
return [torch.stack(list(tup), 0) for tup in zip(*datas)]
def init_weights(m):
if isinstance(m, torch.nn.Linear):
torch.nn.init.uniform_(m.weight)
torch.nn.init.uniform_(m.bias)
### Part 3: loss and hyperparams
def compute_loss(pred, gt):
loss = torch.nn.L1Loss(reduction = 'mean')(pred, gt)
return loss
### Part 4: training and evaluation
def train():
model.train()
losses = []
for batch_id, (input, output) in enumerate(train_loader):
predict = model(input)
loss = compute_loss(predict, output)
losses.append(loss)
optimizer.zero_grad()
loss.backward()
optimizer.step()
scheduler.step(loss)
print('[TRAIN] epoch {}, batch {}, loss: {:4f}'.format(epoch, batch_id + 1, sum(losses) / len(losses)))
def eval():
model.eval()
losses = []
for batch_id, (input, output) in enumerate(eval_loader):
predict = model(input)
loss = compute_loss(predict, output)
losses.append(loss)
print('[EVAL] epoch {}, batch {}, loss: {:4f}'.format(epoch, batch_id + 1, sum(losses) / len(losses)))
if __name__ == '__main__':
### Part 2: read data
dataset_name = 'vh.' + sys.argv[1]
n_threads = 0
train_data = torch.load(dataset_name + '/train.pth')
train_loader = torch.utils.data.DataLoader(train_data,
batch_size = config.batch_size,
num_workers = n_threads,
collate_fn = collate,
shuffle = True,
pin_memory = True)
eval_data = torch.load(dataset_name + '/eval.pth')
eval_loader = torch.utils.data.DataLoader(eval_data,
batch_size = config.batch_size,
num_workers = n_threads,
collate_fn = collate,
shuffle = False,
pin_memory = True)
n_sensors = train_data[0][0].shape[0]
n_chunks = train_data[0][1].shape[0]
# n_sensors = 1
# n_chunks = 1
model = Model(n_sensors, n_chunks)
model.to(device)
resume = 0
if resume:
ckpt = torch.load(dataset_name + '/.pth')
model.load_state_dict(ckpt)
else:
# pass
model.apply(init_weights)
optimizer = torch.optim.SGD(model.parameters(), lr = config.lr)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, config.epochs, config.min_lr)
# scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer)
for epoch in range(1, config.epochs + 1):
train()
if epoch % config.eval_freq == 0:
eval()
if epoch % config.save_freq == 0:
torch.save(model.state_dict(), dataset_name + '/.pth')