-
Notifications
You must be signed in to change notification settings - Fork 0
/
P3_SVHN_model.py
88 lines (67 loc) · 2.06 KB
/
P3_SVHN_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
import torch
import torch.nn as nn
class GRF(torch.autograd.Function):
@staticmethod
def forward(ctx, x, lambda_):
ctx.save_for_backward(torch.tensor(lambda_))
return x.view_as(x) # NECESSARY! autograd checks if tensor is modified
@staticmethod
def backward(ctx, grad_output):
lambda_ = ctx.saved_variables[0]
return grad_output.neg() * lambda_, None
class FeatureExtractor(nn.Module):
def __init__(self, in_chans=3) -> None:
super().__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_chans, 64, kernel_size=4),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(64, 64, kernel_size=5),
nn.BatchNorm2d(64),
nn.Dropout2d(),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(64, 128, kernel_size=3),
)
def forward(self, x):
feature = self.conv(x)
feature = feature.reshape(-1, 128)
return feature
class LabelPredictor(nn.Module):
def __init__(self, n_classes=10) -> None:
super().__init__()
self.l_clf = nn.Sequential(
nn.Linear(128, 1024),
nn.BatchNorm1d(1024),
nn.ReLU(),
nn.Linear(1024, 256),
nn.BatchNorm1d(256),
nn.ReLU(),
nn.Linear(256, n_classes),
)
def forward(self, x):
x = self.l_clf(x)
return x
class DomainClassifier(nn.Module):
'''
A Binary classifier
'''
def __init__(self) -> None:
super().__init__()
self.d_clf = nn.Sequential(
nn.Linear(128, 1024),
nn.BatchNorm1d(1024),
nn.ReLU(),
nn.Linear(1024, 256),
nn.BatchNorm1d(256),
nn.ReLU(),
nn.Linear(256, 1),
)
def forward(self, x, lambda_):
x = GRF.apply(x, lambda_)
x = self.d_clf(x)
return x
if __name__ == '__main__':
n = FeatureExtractor()
n(torch.rand(64, 3, 32, 32))