/
model.py
138 lines (117 loc) · 5 KB
/
model.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
#! /usr/bin/env python
# -*- conding:utf-8 -*-
import chainer
import chainer.links as L
import chainer.functions as F
from chainer import reporter
from chainer import Variable
from chainer.functions.array.reshape import reshape
import cupy as cp
import math
# ひとまずここに書く(後でちゃんと直す予定)
m=0.40
s=30.0
easy_margin=False
cos_m = math.cos(m)
sin_m = math.sin(m)
th = math.cos(math.pi - m)
mm = math.sin(math.pi - m) * m
# ----------------------------------------
# ResNet50(Fine-Tuning)
def _global_average_pooling_2d(x):
n, channel, rows, cols = x.shape
h = F.average_pooling_2d(x, (rows, cols), stride=1)
h = reshape(h, (n, channel))
return h
class ResNet50Fine(chainer.Chain):
def __init__(self, num_class=10):
super(ResNet50Fine, self).__init__()
with self.init_scope():
self.base = L.ResNet50Layers()
self.fc = L.Linear(None, num_class)
self.weight = chainer.Parameter(chainer.initializers.Normal(scale=0.01), (num_class, 2048))
def __call__(self, x, t):
h = self.base(x, layers=['res5'])['res5']
self.cam = h
h = _global_average_pooling_2d(h)
################################################################################
# ResNet50の後ろにArcFace実装
################################################################################
# --------------------------- cos(theta) & phi(theta) ---------------------------
cosine = F.linear(F.normalize(h), F.normalize(self.weight)) # fc8
sine = F.sqrt(F.clip((1.0 - F.square(cosine)),0, 1))
phi = cosine * cos_m - sine * sin_m
if easy_margin:
phi = F.where(cosine.data > 0, phi, cosine)
else:
phi = F.where(cosine.data > th, phi, cosine - mm)
# --------------------------- convert label to one-hot ---------------------------
one_hot = cp.eye(10)[t].astype(cp.float32)
one_hot = Variable(one_hot)
# -------------torch.where(out_i = {x_i if condition_i else y_i) -------------
output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
output *= s
################################################################################
#h = self.fc(h)
return output
"""
class VGG16Fine(chainer.Chain):
def __init__(self, num_class=10):
w = chainer.initializers.Normal(scale=0.01)
super(VGG16Fine, self).__init__()
with self.init_scope():
self.base = L.VGG16Layers()
self.weight = chainer.Parameter(chainer.initializers.Normal(scale=0.01), (num_class, 32))
self.fc6 = L.Linear(None, 1024, initialW=w)
self.fc7 = L.Linear(1024, 32, initialW=w)
#self.fc8 = L.Linear(32, num_class)
def __call__(self, x, t):
h = self.base(x, layers=['conv5_3'])['conv5_3']
self.cam = h
h = F.max_pooling_2d(h, 2, stride=2)
h = F.dropout(h, ratio=0.5)
h = self.fc6(h)
h = F.relu(h)
h = F.dropout(h, ratio=0.5)
h = self.fc7(h)
#h = F.relu(h)
#h = F.dropout(h, ratio=0.5)
#h = self.fc8(h)
################################################################################
# VGG16の後ろにArcFace実装
################################################################################
# --------------------------- cos(theta) & phi(theta) ---------------------------
cosine = F.linear(F.normalize(h), F.normalize(self.weight)) # fc8
sine = F.sqrt(F.clip((1.0 - F.square(cosine)),0, 1))
#print(self.weight)
phi = cosine * cos_m - sine * sin_m
if easy_margin:
phi = F.where(cosine.data > 0, phi, cosine)
else:
phi = F.where(cosine.data > th, phi, cosine - mm)
# --------------------------- convert label to one-hot ---------------------------
one_hot = cp.eye(10)[t].astype(cp.float32)
one_hot = Variable(one_hot)
# -------------torch.where(out_i = {x_i if condition_i else y_i) -------------
output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
output *= s
################################################################################
return output
"""
class ArcFaceClassifer(L.Classifier):
def __init__(self, predictor,
lossfun=F.softmax_cross_entropy,
accfun=F.accuracy,):
super().__init__(predictor=predictor, lossfun=lossfun, accfun=accfun)
def forward(self, x, t):
if not chainer.config.train:
self.y = self.predictor(x, t)
self.loss = self.lossfun(self.y, t)
else:
self.y= self.predictor(x, t)
self.loss = self.lossfun(self.y, t)
reporter.report({'loss': self.loss}, self)
if self.compute_accuracy:
self.accuracy = self.accfun(self.y, t)
reporter.report({'accuracy': self.accuracy}, self)
return self.loss