forked from thuml/Universal-Domain-Adaptation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.py
executable file
·159 lines (135 loc) · 5.2 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
from easydl import *
from torchvision import models
class BaseFeatureExtractor(nn.Module):
def forward(self, *input):
pass
def __init__(self):
super(BaseFeatureExtractor, self).__init__()
def output_num(self):
pass
def train(self, mode=True):
# freeze BN mean and std
for module in self.children():
if isinstance(module, nn.BatchNorm2d):
module.train(False)
else:
module.train(mode)
class ResNet50Fc(BaseFeatureExtractor):
"""
** input image should be in range of [0, 1]**
"""
def __init__(self,model_path=None, normalize=True):
super(ResNet50Fc, self).__init__()
if model_path:
if os.path.exists(model_path):
self.model_resnet = models.resnet50(pretrained=False)
self.model_resnet.load_state_dict(torch.load(model_path))
else:
raise Exception('invalid model path!')
else:
self.model_resnet = models.resnet50(pretrained=True)
if model_path or normalize:
# pretrain model is used, use ImageNet normalization
self.normalize = True
self.register_buffer('mean', torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
self.register_buffer('std', torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
else:
self.normalize = False
model_resnet = self.model_resnet
self.conv1 = model_resnet.conv1
self.bn1 = model_resnet.bn1
self.relu = model_resnet.relu
self.maxpool = model_resnet.maxpool
self.layer1 = model_resnet.layer1
self.layer2 = model_resnet.layer2
self.layer3 = model_resnet.layer3
self.layer4 = model_resnet.layer4
self.avgpool = model_resnet.avgpool
self.__in_features = model_resnet.fc.in_features
def forward(self, x):
if self.normalize:
x = (x - self.mean) / self.std
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
return x
def output_num(self):
return self.__in_features
class VGG16Fc(BaseFeatureExtractor):
def __init__(self,model_path=None, normalize=True):
super(VGG16Fc, self).__init__()
if model_path:
if os.path.exists(model_path):
self.model_vgg = models.vgg16(pretrained=False)
self.model_vgg.load_state_dict(torch.load(model_path))
else:
raise Exception('invalid model path!')
else:
self.model_vgg = models.vgg16(pretrained=True)
if model_path or normalize:
# pretrain model is used, use ImageNet normalization
self.normalize = True
self.register_buffer('mean', torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
self.register_buffer('std', torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
else:
self.normalize = False
model_vgg = self.model_vgg
self.features = model_vgg.features
self.classifier = nn.Sequential()
for i in range(6):
self.classifier.add_module("classifier"+str(i), model_vgg.classifier[i])
self.feature_layers = nn.Sequential(self.features, self.classifier)
self.__in_features = 4096
def forward(self, x):
if self.normalize:
x = (x - self.mean) / self.std
x = self.features(x)
x = x.view(x.size(0), 25088)
x = self.classifier(x)
return x
def output_num(self):
return self.__in_features
class CLS(nn.Module):
"""
a two-layer MLP for classification
"""
def __init__(self, in_dim, out_dim, bottle_neck_dim=256):
super(CLS, self).__init__()
self.bottleneck = nn.Linear(in_dim, bottle_neck_dim)
self.fc = nn.Linear(bottle_neck_dim, out_dim)
self.main = nn.Sequential(self.bottleneck, self.fc, nn.Softmax(dim=-1))
def forward(self, x):
out = [x]
for module in self.main.children():
x = module(x)
out.append(x)
return out
class AdversarialNetwork(nn.Module):
"""
AdversarialNetwork with a gredient reverse layer.
its ``forward`` function calls gredient reverse layer first, then applies ``self.main`` module.
"""
def __init__(self, in_feature):
super(AdversarialNetwork, self).__init__()
self.main = nn.Sequential(
nn.Linear(in_feature, 1024),
nn.ReLU(inplace=True),
nn.Dropout(0.5),
nn.Linear(1024,1024),
nn.ReLU(inplace=True),
nn.Dropout(0.5),
nn.Linear(1024, 1),
nn.Sigmoid()
)
self.grl = GradientReverseModule(lambda step: aToBSheduler(step, 0.0, 1.0, gamma=10, max_iter=10000))
def forward(self, x):
x_ = self.grl(x)
y = self.main(x_)
return y