-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetClasses.py
189 lines (157 loc) · 5.83 KB
/
netClasses.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
import pickle as pkl
import torch
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
from importlib import reload
class FFNet(nn.Module):
def __init__(self, num_feats, out_size):
super(FFNet, self).__init__()
layer1_chan = 50
layer2_chan = 50
layer3_chan = 50
drop_out_prob = 0.50
self.drop_out = nn.Dropout(p=drop_out_prob)
self.fc1 = nn.Linear(num_feats, layer1_chan)
self.norm_1 = nn.BatchNorm1d(layer1_chan)
self.fc2 = nn.Linear(layer1_chan, layer2_chan)
self.norm_2 = nn.BatchNorm1d(layer2_chan)
self.fc3 = nn.Linear(layer2_chan, out_size)
self.relu = nn.ReLU()
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.norm_1(out)
out = self.drop_out(out)
out = self.fc2(out)
out = self.relu(out)
out = self.norm_2(out)
out = self.drop_out(out)
out = self.fc3(out)
return out
class FFNetDistance(nn.Module):
def __init__(self, num_feats, dim_size=10):
super(FFNetDistance, self).__init__()
layer1_chan = 100
layer2_chan = 100
layer3_chan = dim_size
drop_out_prob = 0.25
self.layer1 = nn.Sequential(
nn.Linear(num_feats, layer1_chan),
nn.ReLU(),
nn.BatchNorm1d(layer1_chan),
nn.Dropout(p=drop_out_prob)
)
self.layer2 = nn.Sequential(
nn.Linear(layer1_chan, layer2_chan),
nn.ReLU(),
nn.BatchNorm1d(layer2_chan),
nn.Dropout(p=drop_out_prob)
)
self.layer3 = nn.Sequential(
nn.Linear(layer2_chan, layer3_chan)
)
self.dist = nn.PairwiseDistance(p=1.0)
def forward(self, x):
f0 = x[:, 0, :]
f1 = x[:, 1, :]
out0 = self.layer1(x[:, 0, :])
out0 = self.layer2(out0)
out0 = self.layer3(out0)
out1 = self.layer1(x[:, 1, :])
out1 = self.layer2(out1)
out1 = self.layer3(out1)
distance = self.dist(out1, out0)
return distance
def subspace(self, x):
out0 = self.layer1(x)
out0 = self.layer2(out0)
out0 = self.layer3(out0)
return out0
class ConvNet(nn.Module):
def __init__(self, img_size, out_size):
super(ConvNet, self).__init__()
layer1_chan = 100
layer2_chan = 100
hidden_layer = 500
conv1_kwargs = {'kernel_size':5, 'stride':1, 'padding':(0,4), 'dilation':1}
max1_kwargs = {'kernel_size':2, 'stride':2}
conv2_kwargs = {'kernel_size':5, 'stride':1, 'padding':(0,4), 'dilation':1}
max2_kwargs = max1_kwargs
def get_new_size(old_size, kernel_size=3, padding=0, dilation=1, stride=None):
if type(kernel_size) is not tuple:
kernel_size = (kernel_size, kernel_size)
if not stride:
stride = kernel_size
if type(stride) is not tuple:
stride = (stride, stride)
if type(padding) is not tuple:
padding = (padding, padding)
if type(dilation) is not tuple:
dilation = (dilation, dilation)
# print(kernel_size, stride, padding, dilation)
h_out = (old_size[0] + (2 * padding[0]) - (dilation[0] * (kernel_size[0] - 1)) - 1) / (stride[0]) + 1
v_out = (old_size[1] + (2 * padding[1]) - (dilation[1] * (kernel_size[1] - 1)) - 1) / (stride[1]) + 1
return int(np.floor(h_out)), int(np.floor(v_out))
self.layer1 = nn.Sequential(
nn.Conv2d(1, layer1_chan, **conv1_kwargs),
nn.ReLU(),
nn.MaxPool2d(**max1_kwargs),
nn.BatchNorm2d(layer1_chan)
)
self.drop_out_2d = nn.Dropout2d()
self.layer2 = nn.Sequential(
nn.Conv2d(layer1_chan, layer2_chan, **conv2_kwargs),
nn.ReLU(),
nn.MaxPool2d(**max2_kwargs),
nn.BatchNorm2d(layer1_chan)
)
self.drop_out = nn.Dropout()
new_size = get_new_size(img_size, **conv1_kwargs)
new_size = get_new_size(new_size, **max1_kwargs)
new_size = get_new_size(new_size, **conv2_kwargs)
new_size = get_new_size(new_size, **max2_kwargs)
self.fc1 = nn.Linear(new_size[0] * new_size[1] * layer2_chan, hidden_layer)
self.fc2 = nn.Linear(hidden_layer, out_size)
def forward(self, x):
out = self.layer1(x)
out = self.drop_out_2d(out)
out = self.layer2(out)
out = out.reshape(out.size(0), -1)
out = self.drop_out(out)
out = self.fc1(out)
out = self.fc2(out)
return out
if __name__ == '__main__':
# put garbage data thru a net to make sure it's working
# (i.e. capable of overfitting)
learning_rate = 2e-4
num_feats = 106
batch_size = 500
epochs = 2000
model = FFNetDistance(num_feats)
loss_func = nn.HingeEmbeddingLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
x = torch.rand(batch_size, 2, num_feats)
y = torch.randint(0, 2, (batch_size,)) * 2 - 1
for epoch in range(epochs):
y_pred = model(x)
loss = loss_func(y_pred, y)
# Reset gradients to zero, perform a backward pass, and update the weights
optimizer.zero_grad()
loss.backward()
optimizer.step()
rd_loss = np.round(loss.item(), 4)
if not epoch % 100:
print(f"Epoch : {epoch} Loss : {rd_loss}")
model.eval()
with torch.no_grad():
for ind in range(batch_size):
diff = abs(model.subspace(x[ind][0]) - model.subspace(x[ind][1]))
distance = sum(diff).item()
print(distance, y[ind])