-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain.py
146 lines (102 loc) · 3.81 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import numpy as np
import torch
from torch.nn.utils import rnn as rnn_utils
from torch.utils.data import DataLoader
from typing import NamedTuple
from xor_dataset import XORDataset
from utils import get_arguments
class ModelParams(NamedTuple):
# data
max_bits: int = 50
vary_lengths: bool = False
# train loop
batch_size: int = 8
device: str = 'cuda:0' if torch.cuda.is_available() else 'cpu'
epochs: int = 2
momentum: float = 0
# lstm
hidden_size: int = 2
lr: float = 1
num_layers: int = 1
# make it deterministic
torch.manual_seed(0)
class LSTM(torch.nn.Module):
def __init__(self, params: ModelParams):
super().__init__()
self._params = params
self.lstm = torch.nn.LSTM(
batch_first=True,
input_size=1,
hidden_size=params.hidden_size,
num_layers=params.num_layers)
self.hidden_to_logits = torch.nn.Linear(params.hidden_size, 1)
self.activation = torch.nn.Sigmoid()
def forward(self, inputs, lengths):
# pack the inputs
packed_inputs = rnn_utils.pack_padded_sequence(
inputs, lengths, batch_first=True).to(params.device)
lstm_out, _ = self.lstm(packed_inputs)
unpacked, _ = rnn_utils.pad_packed_sequence(lstm_out, batch_first=True)
logits = self.hidden_to_logits(unpacked)
predictions = self.activation(logits)
return logits, predictions
def train(params: ModelParams):
model = LSTM(params).to(params.device)
optimizer = torch.optim.SGD(model.parameters(), lr=params.lr, momentum=params.momentum)
loss_fn = torch.nn.BCEWithLogitsLoss()
train_loader = DataLoader(XORDataset(num_bits=params.max_bits), batch_size=params.batch_size)
step = 0
for epoch in range(1, params.epochs + 1):
for inputs, targets in train_loader:
lengths = adjust_lengths(params.vary_lengths, inputs, targets)
targets = targets.to(params.device)
optimizer.zero_grad()
logits, predictions = model(inputs, lengths)
# BCEWithLogitsLoss will do the activation
loss = loss_fn(logits, targets)
loss.backward()
optimizer.step()
step += 1
accuracy = ((predictions > 0.5) == (targets > 0.5)).type(torch.FloatTensor).mean()
if step % 250 == 0:
print(f'epoch {epoch}, step {step}, loss {loss.item():.{4}f}, accuracy {accuracy:.{3}f}')
if step % 1000 == 0:
test_accuracy = evaluate(params, model)
print(f'test accuracy {test_accuracy:.{3}f}')
if test_accuracy == 1.0:
# stop early
break
def adjust_lengths(vary_lengths, inputs, targets):
batch_size = inputs.size()[0]
max_bits = inputs.size()[1]
if not vary_lengths:
lengths = torch.ones(batch_size, dtype=torch.int) * max_bits
return lengths
# choose random lengths
lengths = np.random.randint(1, max_bits, size=batch_size, dtype=int)
# keep one the max size so we don't need to resize targets for the loss
lengths[0] = max_bits
# sort in descending order
lengths = -np.sort(-lengths)
# chop the bits based on lengths
for i, sample_length in enumerate(lengths):
inputs[i, lengths[i]:, ] = 0
targets[i, lengths[i]:, ] = 0
return lengths
def evaluate(params, model):
# evaluate on more bits than training to ensure generalization
test_loader = DataLoader(
XORDataset(num_sequences=5000, num_bits=int(params.max_bits * 1.5)), batch_size=500)
is_correct = np.array([])
for inputs, targets in test_loader:
lengths = adjust_lengths(params.vary_lengths, inputs, targets)
inputs = inputs.to(params.device)
targets = targets.to(params.device)
with torch.no_grad():
logits, predictions = model(inputs, lengths)
is_correct = np.append(is_correct, ((predictions > 0.5) == (targets > 0.5)))
accuracy = is_correct.mean()
return accuracy
if __name__ == '__main__':
params = get_arguments(ModelParams)
train(params)