-
Notifications
You must be signed in to change notification settings - Fork 73
/
net.py
280 lines (227 loc) · 10.8 KB
/
net.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
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
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from torch.optim import lr_scheduler
from torch.autograd import Variable
def squash(x):
lengths2 = x.pow(2).sum(dim=2)
lengths = lengths2.sqrt()
x = x * (lengths2 / (1 + lengths2) / lengths).view(x.size(0), x.size(1), 1)
return x
class AgreementRouting(nn.Module):
def __init__(self, input_caps, output_caps, n_iterations):
super(AgreementRouting, self).__init__()
self.n_iterations = n_iterations
self.b = nn.Parameter(torch.zeros((input_caps, output_caps)))
def forward(self, u_predict):
batch_size, input_caps, output_caps, output_dim = u_predict.size()
c = F.softmax(self.b)
s = (c.unsqueeze(2) * u_predict).sum(dim=1)
v = squash(s)
if self.n_iterations > 0:
b_batch = self.b.expand((batch_size, input_caps, output_caps))
for r in range(self.n_iterations):
v = v.unsqueeze(1)
b_batch = b_batch + (u_predict * v).sum(-1)
c = F.softmax(b_batch.view(-1, output_caps)).view(-1, input_caps, output_caps, 1)
s = (c * u_predict).sum(dim=1)
v = squash(s)
return v
class CapsLayer(nn.Module):
def __init__(self, input_caps, input_dim, output_caps, output_dim, routing_module):
super(CapsLayer, self).__init__()
self.input_dim = input_dim
self.input_caps = input_caps
self.output_dim = output_dim
self.output_caps = output_caps
self.weights = nn.Parameter(torch.Tensor(input_caps, input_dim, output_caps * output_dim))
self.routing_module = routing_module
self.reset_parameters()
def reset_parameters(self):
stdv = 1. / math.sqrt(self.input_caps)
self.weights.data.uniform_(-stdv, stdv)
def forward(self, caps_output):
caps_output = caps_output.unsqueeze(2)
u_predict = caps_output.matmul(self.weights)
u_predict = u_predict.view(u_predict.size(0), self.input_caps, self.output_caps, self.output_dim)
v = self.routing_module(u_predict)
return v
class PrimaryCapsLayer(nn.Module):
def __init__(self, input_channels, output_caps, output_dim, kernel_size, stride):
super(PrimaryCapsLayer, self).__init__()
self.conv = nn.Conv2d(input_channels, output_caps * output_dim, kernel_size=kernel_size, stride=stride)
self.input_channels = input_channels
self.output_caps = output_caps
self.output_dim = output_dim
def forward(self, input):
out = self.conv(input)
N, C, H, W = out.size()
out = out.view(N, self.output_caps, self.output_dim, H, W)
# will output N x OUT_CAPS x OUT_DIM
out = out.permute(0, 1, 3, 4, 2).contiguous()
out = out.view(out.size(0), -1, out.size(4))
out = squash(out)
return out
class CapsNet(nn.Module):
def __init__(self, routing_iterations, n_classes=10):
super(CapsNet, self).__init__()
self.conv1 = nn.Conv2d(1, 256, kernel_size=9, stride=1)
self.primaryCaps = PrimaryCapsLayer(256, 32, 8, kernel_size=9, stride=2) # outputs 6*6
self.num_primaryCaps = 32 * 6 * 6
routing_module = AgreementRouting(self.num_primaryCaps, n_classes, routing_iterations)
self.digitCaps = CapsLayer(self.num_primaryCaps, 8, n_classes, 16, routing_module)
def forward(self, input):
x = self.conv1(input)
x = F.relu(x)
x = self.primaryCaps(x)
x = self.digitCaps(x)
probs = x.pow(2).sum(dim=2).sqrt()
return x, probs
class ReconstructionNet(nn.Module):
def __init__(self, n_dim=16, n_classes=10):
super(ReconstructionNet, self).__init__()
self.fc1 = nn.Linear(n_dim * n_classes, 512)
self.fc2 = nn.Linear(512, 1024)
self.fc3 = nn.Linear(1024, 784)
self.n_dim = n_dim
self.n_classes = n_classes
def forward(self, x, target):
mask = Variable(torch.zeros((x.size()[0], self.n_classes)), requires_grad=False)
if next(self.parameters()).is_cuda:
mask = mask.cuda()
mask.scatter_(1, target.view(-1, 1), 1.)
mask = mask.unsqueeze(2)
x = x * mask
x = x.view(-1, self.n_dim * self.n_classes)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.sigmoid(self.fc3(x))
return x
class CapsNetWithReconstruction(nn.Module):
def __init__(self, capsnet, reconstruction_net):
super(CapsNetWithReconstruction, self).__init__()
self.capsnet = capsnet
self.reconstruction_net = reconstruction_net
def forward(self, x, target):
x, probs = self.capsnet(x)
reconstruction = self.reconstruction_net(x, target)
return reconstruction, probs
class MarginLoss(nn.Module):
def __init__(self, m_pos, m_neg, lambda_):
super(MarginLoss, self).__init__()
self.m_pos = m_pos
self.m_neg = m_neg
self.lambda_ = lambda_
def forward(self, lengths, targets, size_average=True):
t = torch.zeros(lengths.size()).long()
if targets.is_cuda:
t = t.cuda()
t = t.scatter_(1, targets.data.view(-1, 1), 1)
targets = Variable(t)
losses = targets.float() * F.relu(self.m_pos - lengths).pow(2) + \
self.lambda_ * (1. - targets.float()) * F.relu(lengths - self.m_neg).pow(2)
return losses.mean() if size_average else losses.sum()
if __name__ == '__main__':
import argparse
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
# Training settings
parser = argparse.ArgumentParser(description='CapsNet with MNIST')
parser.add_argument('--batch-size', type=int, default=128, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=250, metavar='N',
help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.001, metavar='LR',
help='learning rate (default: 0.01)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--routing_iterations', type=int, default=3)
parser.add_argument('--with_reconstruction', action='store_true', default=False)
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
kwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([
transforms.Pad(2), transforms.RandomCrop(28),
transforms.ToTensor()
])),
batch_size=args.batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=False, transform=transforms.Compose([
transforms.ToTensor()
])),
batch_size=args.test_batch_size, shuffle=False, **kwargs)
model = CapsNet(args.routing_iterations)
if args.with_reconstruction:
reconstruction_model = ReconstructionNet(16, 10)
reconstruction_alpha = 0.0005
model = CapsNetWithReconstruction(model, reconstruction_model)
if args.cuda:
model.cuda()
optimizer = optim.Adam(model.parameters(), lr=args.lr)
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, verbose=True, patience=15, min_lr=1e-6)
loss_fn = MarginLoss(0.9, 0.1, 0.5)
def train(epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
if args.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data), Variable(target, requires_grad=False)
optimizer.zero_grad()
if args.with_reconstruction:
output, probs = model(data, target)
reconstruction_loss = F.mse_loss(output, data.view(-1, 784))
margin_loss = loss_fn(probs, target)
loss = reconstruction_alpha * reconstruction_loss + margin_loss
else:
output, probs = model(data)
loss = loss_fn(probs, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.data[0]))
def test():
model.eval()
test_loss = 0
correct = 0
for data, target in test_loader:
if args.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data, volatile=True), Variable(target)
if args.with_reconstruction:
output, probs = model(data, target)
reconstruction_loss = F.mse_loss(output, data.view(-1, 784), size_average=False).data[0]
test_loss += loss_fn(probs, target, size_average=False).data[0]
test_loss += reconstruction_alpha * reconstruction_loss
else:
output, probs = model(data)
test_loss += loss_fn(probs, target, size_average=False).data[0]
pred = probs.data.max(1, keepdim=True)[1] # get the index of the max probability
correct += pred.eq(target.data.view_as(pred)).cpu().sum()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
return test_loss
for epoch in range(1, args.epochs + 1):
train(epoch)
test_loss = test()
scheduler.step(test_loss)
torch.save(model.state_dict(),
'{:03d}_model_dict_{}routing_reconstruction{}.pth'.format(epoch, args.routing_iterations,
args.with_reconstruction))