Repository navigation
Expand file tree
/
Copy pathmodel.py
More file actions
338 lines (251 loc) · 10.5 KB
/
Copy pathmodel.py
File metadata and controls
338 lines (251 loc) · 10.5 KB
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import itertools
from tqdm import tqdm
from utils import FFDataset, SoftmaxDataset
class FFLayer(nn.Module):
def __init__(self, in_dims, out_dims, threshold, lr, batch_size, epochs, dropout, device):
super().__init__()
self.linear = nn.Linear(in_dims, out_dims)
self.dropout = nn.Dropout(dropout)
self.opt = torch.optim.Adam(self.parameters(), lr=lr)
self.threshold = threshold
self.batch_size = batch_size
self.epochs = epochs
self.device = device
self.criterion = nn.BCEWithLogitsLoss()
def normalize(self, x):
return x / (x.norm(p=2, dim=1, keepdim=True) + 1e-7)
def forward(self, x):
x = self.normalize(x)
return F.relu(self.dropout(self.linear(x)))
def train_layer(self, h_pos, h_neg):
dataset = FFDataset(h_pos, h_neg)
dataloader = DataLoader(
dataset, batch_size=self.batch_size, shuffle=True)
bar = tqdm(range(self.epochs))
loss_history = []
for _ in bar:
epoch_loss = 0
for h_pos_batch, h_neg_batch in dataloader:
g_pos = self(h_pos_batch).pow(2).sum(1)
g_neg = self(h_neg_batch).pow(2).sum(1)
loss = self.criterion(torch.cat([g_pos-self.threshold, g_neg-self.threshold]),
torch.cat([torch.ones((g_pos.shape[0]), device=self.device),
torch.zeros((g_neg.shape[0]), device=self.device)]))
self.opt.zero_grad()
loss.backward()
self.opt.step()
epoch_loss += loss.item()
epoch_loss /= len(dataloader)
bar.set_postfix({'Loss': epoch_loss})
loss_history.append(epoch_loss)
self.eval()
h_pos = self(h_pos)
h_neg = self(h_neg)
return h_pos.detach(), h_neg.detach(), loss_history
class FFNN(nn.Module):
def __init__(self, dims, threshold, lr, batch_size, epochs, dropout, device):
super().__init__()
self.fflayers = nn.ModuleList()
for d in range(len(dims) - 1):
self.fflayers.append(
FFLayer(dims[d], dims[d+1], threshold, lr, batch_size, epochs, dropout, device))
def train_net(self, x_pos, x_neg):
h_pos, h_neg = x_pos, x_neg
pos_outputs = []
total_loss_history = []
for i, layer in enumerate(self.fflayers):
print(f'Training {i} ff-layer')
layer.train()
h_pos, h_neg, loss_history = layer.train_layer(h_pos, h_neg)
pos_outputs.append(h_pos)
total_loss_history.append(loss_history)
return pos_outputs, total_loss_history
def predict(self, x):
outputs = []
for i, layer in enumerate(self.fflayers):
layer.eval()
x = layer(x)
outputs.append(x)
return outputs
class LocalConv(nn.Module):
def __init__(self,
out_channels,
input_shape,
kernel_size,
strides,
bias=False,
):
super().__init__()
self.out_channels = out_channels
self.kernel_size = kernel_size
self.strides = strides
self.bias = bias
input_row, input_col = input_shape[1:]
input_filter = input_shape[0]
output_row = self.output_length(
input_row, self.kernel_size[0], self.strides[0])
output_col = self.output_length(
input_col, self.kernel_size[1], self.strides[1])
self.output_shape = (output_row, output_col)
self.kernel_shape = (output_row * output_col,
self.kernel_size[0] *
self.kernel_size[1] * input_filter,
self.out_channels
)
self.kernel = nn.Parameter(torch.randn(self.kernel_shape))
if self.bias:
self.bias_shape = (self.out_channels, output_row, output_col)
self.bias = nn.Parameter(torch.randn(self.bias_shape))
def output_length(self, input_length, kernel_size, stride):
output_length = input_length - kernel_size + 1
return (output_length + stride - 1) // stride
def forward(self, inputs):
feature_dim = self.kernel_shape[1]
channels_out = self.kernel_shape[-1]
xs = []
output_axes_ticks = [range(axis_max) for axis_max in self.output_shape]
for position in itertools.product(*output_axes_ticks):
slices = [slice(None)]
slices.append(slice(None))
slices.extend(
slice(
position[d] * self.strides[d],
position[d] * self.strides[d] + self.kernel_size[d],
)
for d in [0, 1]
)
xs.append(torch.reshape(inputs[slices], (1, -1, feature_dim)))
x_aggregate = torch.cat(xs)
output = torch.bmm(x_aggregate, self.kernel)
output = torch.reshape(
output, (self.output_shape + (-1, channels_out)))
output = torch.permute(output, (2, 3, 0, 1))
if self.bias is not False:
output = output + self.bias.unsqueeze(0)
return output
class FFRFLayer(nn.Module):
def __init__(self,
out_channel,
input_shape,
kernel_size,
strides,
threshold,
lr,
batch_size,
epochs,
dropout,
device
):
super().__init__()
self.local_conv = LocalConv(
out_channel, input_shape, kernel_size, strides, bias=False)
self.dropout = nn.Dropout(dropout)
self.peer_norm = nn.BatchNorm2d(out_channel)
self.opt = torch.optim.Adam(self.parameters(), lr=lr)
self.threshold = threshold
self.batch_size = batch_size
self.epochs = epochs
self.device = device
self.criterion = nn.BCEWithLogitsLoss()
def forward(self, x):
x = x / (x.norm(p=2, dim=(1, 2, 3), keepdim=True) + 1e-7)
return F.relu(self.dropout(self.peer_norm(self.local_conv(x))))
def train_layer(self, h_pos, h_neg):
dataset = FFDataset(h_pos, h_neg)
dataloader = DataLoader(
dataset, batch_size=self.batch_size, shuffle=True)
bar = tqdm(range(self.epochs))
loss_history = []
for _ in bar:
epoch_loss = 0
for h_pos_batch, h_neg_batch in dataloader:
g_pos = self(h_pos_batch).pow(2).mean(dim=(1, 2, 3))
g_neg = self(h_neg_batch).pow(2).mean(dim=(1, 2, 3))
loss = self.criterion(torch.cat([g_pos-self.threshold, g_neg-self.threshold]),
torch.cat([torch.ones((g_pos.shape[0]), device=self.device),
torch.zeros((g_neg.shape[0]), device=self.device)]))
self.opt.zero_grad()
loss.backward()
self.opt.step()
epoch_loss += loss.item()
epoch_loss /= len(dataloader)
bar.set_postfix({'Loss': epoch_loss})
loss_history.append(epoch_loss)
self.eval()
h_pos = self(h_pos)
h_neg = self(h_neg)
return h_pos.detach(), h_neg.detach(), loss_history
class FFRFNN(nn.Module):
def __init__(self,
out_channel_list,
input_shape_list,
kernel_size_list,
strides_list,
threshold,
lr,
batch_size,
epochs,
dropout,
device
):
super().__init__()
self.fflayers = nn.ModuleList()
for d in range(len(out_channel_list)):
self.fflayers.append(
FFRFLayer(out_channel_list[d], input_shape_list[d], kernel_size_list[d], strides_list[d], threshold, lr, batch_size, epochs, dropout, device))
def train_net(self, x_pos, x_neg):
h_pos, h_neg = x_pos, x_neg
pos_outputs = []
total_loss_history = []
for i, layer in enumerate(self.fflayers):
print(f'Training {i} ff-layer')
layer.train()
h_pos, h_neg, loss_history = layer.train_layer(h_pos, h_neg)
pos_outputs.append(h_pos)
total_loss_history.append(loss_history)
return pos_outputs, total_loss_history
def predict(self, x):
outputs = []
for i, layer in enumerate(self.fflayers):
layer.eval()
x = layer(x)
outputs.append(x)
return outputs
class SoftmaxLayer(nn.Module):
def __init__(self, in_dim, out_dim, lr, batch_size, epochs):
super().__init__()
self.linear = nn.Linear(in_dim, out_dim)
self.criterion = nn.CrossEntropyLoss()
self.opt = torch.optim.Adam(self.parameters(), lr=lr)
self.batch_size = batch_size
self.epochs = epochs
def forward(self, x):
return self.linear(x)
def train_layer(self, x, y):
dataset = SoftmaxDataset(x, y)
dataloader = DataLoader(
dataset, batch_size=self.batch_size, shuffle=True)
bar = tqdm(range(self.epochs))
history = {'loss': [], 'acc': []}
self.train()
for _ in bar:
epoch_loss = 0
epoch_acc = 0
for x, y in dataloader:
x_ = self.forward(x)
loss = self.criterion(x_, y)
self.opt.zero_grad()
loss.backward()
self.opt.step()
epoch_loss += loss.item()
epoch_acc += (torch.argmax(x_, 1) == y).float().mean().item()
epoch_loss /= len(dataloader)
epoch_acc /= len(dataloader)
bar.set_postfix({'Loss': epoch_loss, 'Acc': epoch_acc})
history['loss'].append(epoch_loss)
history['acc'].append(epoch_acc)
return history