-
Notifications
You must be signed in to change notification settings - Fork 82
/
capsule_net_detector.py
271 lines (219 loc) · 9.52 KB
/
capsule_net_detector.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
'''
# author: Zhiyuan Yan
# email: [email protected]
# date: 2023-0706
# description: Class for the CapsuleNetDetector
Functions in the Class are summarized as:
1. __init__: Initialization
2. build_backbone: Backbone-building
3. build_loss: Loss-function-building
4. features: Feature-extraction
5. classifier: Classification
6. get_losses: Loss-computation
7. get_train_metrics: Training-metrics-computation
8. get_test_metrics: Testing-metrics-computation
9. forward: Forward-propagation
Reference:
@inproceedings{nguyen2019capsule,
title={Capsule-forensics: Using capsule networks to detect forged images and videos},
author={Nguyen, Huy H and Yamagishi, Junichi and Echizen, Isao},
booktitle={ICASSP 2019-2019 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
pages={2307--2311},
year={2019},
organization={IEEE}
}
GitHub Reference:
https://github.com/niyunsheng/CORE
'''
import os
import datetime
import numpy as np
from sklearn import metrics
from typing import Union
from collections import defaultdict
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn import DataParallel
from torch.utils.tensorboard import SummaryWriter
from metrics.base_metrics_class import calculate_metrics_for_train
from .base_detector import AbstractDetector
from detectors import DETECTOR
from networks import BACKBONE
from loss import LOSSFUNC
import torchvision.models as models
@DETECTOR.register_module(module_name='capsule_net')
class CapsuleNetDetector(AbstractDetector):
def __init__(self, config):
super().__init__()
self.config = config
self.backbone = self.build_backbone(config)
self.loss_func = self.build_loss(config)
#capsule net
self.num_classes = config['num_classes']
self.vgg_ext = VggExtractor()
self.fea_ext = FeatureExtractor()
self.fea_ext.apply(self.weights_init)
self.NO_CAPS = 10
self.routing_stats = RoutingLayer(num_input_capsules=self.NO_CAPS, num_output_capsules= self.num_classes, data_in=8, data_out=4, num_iterations=2)
def build_backbone(self, config):
... # do not need one specific backbone for capsule net
def build_loss(self, config):
# prepare the loss function
loss_class = LOSSFUNC[config['loss_func']]
loss_func = loss_class()
return loss_func
def features(self, data_dict: dict) -> torch.tensor:
input = self.vgg_ext(data_dict['image'])
feature = self.fea_ext(input)
return feature
def classifier(self, features: torch.tensor) -> torch.tensor:
z = self.routing_stats(features, random = False, dropout = 0.0)
# z[b, data, out_caps]
classes = F.softmax(z, dim=-1)
class_ = classes.detach()
class_ = class_.mean(dim=1)
return classes, class_
def get_losses(self, data_dict: dict, pred_dict: dict) -> dict:
label = data_dict['label']
pred = pred_dict['cls']
classes = pred_dict['classes']
loss = self.loss_func(classes, label)
loss_dict = {'overall': loss}
return loss_dict
def get_train_metrics(self, data_dict: dict, pred_dict: dict) -> dict:
label = data_dict['label']
pred = pred_dict['cls']
# compute metrics for batch data
auc, eer, acc, ap = calculate_metrics_for_train(label.detach(), pred.detach())
metric_batch_dict = {'acc': acc, 'auc': auc, 'eer': eer, 'ap': ap}
return metric_batch_dict
def forward(self, data_dict: dict, inference=False) -> dict:
# get the features by backbone
features = self.features(data_dict)
# get the prediction by classifier
preds, pred = self.classifier(features)
# get the probability of the pred
prob = torch.softmax(pred, dim=1)[:, 1]
# build the prediction dict for each output
pred_dict = {'cls': pred, 'prob': prob, 'feat': features, 'classes': preds}
return pred_dict
def weights_init(self, m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
# VGG input(10,3,256,256)
class VggExtractor(nn.Module):
def __init__(self, train=False):
super(VggExtractor, self).__init__()
self.vgg_1 = self.Vgg(models.vgg19(pretrained=True), 0, 18)
if train:
self.vgg_1.train(mode=True)
self.freeze_gradient()
else:
self.vgg_1.eval()
def Vgg(self, vgg, begin, end):
features = nn.Sequential(*list(vgg.features.children())[begin:(end+1)])
return features
def freeze_gradient(self, begin=0, end=9):
for i in range(begin, end+1):
self.vgg_1[i].requires_grad = False
def forward(self, input):
return self.vgg_1(input)
class FeatureExtractor(nn.Module):
def __init__(self):
super(FeatureExtractor, self).__init__()
self.NO_CAPS = 10 ##mark yxh
self.capsules = nn.ModuleList([
nn.Sequential(
nn.Conv2d(256, 64, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 16, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(16),
nn.ReLU(),
StatsNet(),
nn.Conv1d(2, 8, kernel_size=5, stride=2, padding=2),
nn.BatchNorm1d(8),
nn.Conv1d(8, 1, kernel_size=3, stride=1, padding=1),
nn.BatchNorm1d(1),
View(-1, 8),
)
for _ in range(self.NO_CAPS)]
)
def squash(self, tensor, dim):
squared_norm = (tensor ** 2).sum(dim=dim, keepdim=True)
scale = squared_norm / (1 + squared_norm)
return scale * tensor / (torch.sqrt(squared_norm))
def forward(self, x):
# outputs = [capsule(x.detach()) for capsule in self.capsules]
# outputs = [capsule(x.clone()) for capsule in self.capsules]
outputs = [capsule(x) for capsule in self.capsules]
output = torch.stack(outputs, dim=-1)
return self.squash(output, dim=-1)
class StatsNet(nn.Module):
def __init__(self):
super(StatsNet, self).__init__()
def forward(self, x):
x = x.view(x.data.shape[0], x.data.shape[1], x.data.shape[2]*x.data.shape[3])
mean = torch.mean(x, 2)
std = torch.std(x, 2)
return torch.stack((mean, std), dim=1)
class View(nn.Module):
def __init__(self, *shape):
super(View, self).__init__()
self.shape = shape
def forward(self, input):
return input.view(self.shape)
# Capsule right Dynamic routing
class RoutingLayer(nn.Module):
def __init__(self, num_input_capsules, num_output_capsules, data_in, data_out, num_iterations):
super(RoutingLayer, self).__init__()
self.num_iterations = num_iterations
self.route_weights = nn.Parameter(torch.randn(num_output_capsules, num_input_capsules, data_out, data_in))
def squash(self, tensor, dim):
squared_norm = (tensor ** 2).sum(dim=dim, keepdim=True)
scale = squared_norm / (1 + squared_norm)
return scale * tensor / (torch.sqrt(squared_norm))
def forward(self, x, random, dropout):
# x[b, data, in_caps]
x = x.transpose(2, 1)
# x[b, in_caps, data]
if random:
# noise = torch.Tensor(0.01*torch.randn(*self.route_weights.size())).cuda()
noise = torch.Tensor(0.01*torch.randn(*self.route_weights.size())).cuda()
route_weights = self.route_weights + noise
else:
route_weights = self.route_weights
priors = route_weights[:, None, :, :, :] @ x[None, :, :, :, None]
# route_weights [out_caps , 1 , in_caps , data_out , data_in]
# x [ 1 , b , in_caps , data_in , 1 ]
# priors [out_caps , b , in_caps , data_out, 1 ]
priors = priors.transpose(1, 0)
# priors[b, out_caps, in_caps, data_out, 1]
if dropout > 0.0:
# drop = torch.Tensor(torch.FloatTensor(*priors.size()).bernoulli(1.0- dropout)).cuda()
drop = torch.Tensor(torch.FloatTensor(*priors.size()).bernoulli(1.0- dropout)).cuda()
priors = priors * drop
# logits = torch.Tensor(torch.zeros(*priors.size())).cuda()
logits = torch.Tensor(torch.zeros(*priors.size())).to(priors.device)
# logits[b, out_caps, in_caps, data_out, 1]
num_iterations = self.num_iterations
for i in range(num_iterations):
probs = F.softmax(logits, dim=2)
outputs = self.squash((probs * priors).sum(dim=2, keepdim=True), dim=3)
if i != self.num_iterations - 1:
delta_logits = priors * outputs
logits = logits + delta_logits
# outputs[b, out_caps, 1, data_out, 1]
outputs = outputs.squeeze()
if len(outputs.shape) == 3:
outputs = outputs.transpose(2, 1).contiguous()
else:
outputs = outputs.unsqueeze_(dim=0).transpose(2, 1).contiguous()
# outputs[b, data_out, out_caps]
return outputs