forked from hanzhaoml/MDAN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
170 lines (157 loc) · 6.96 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
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
# #!/usr/bin/env python
# # -*- coding: utf-8 -*-
#
# import logging
# import torch
# import torch.nn as nn
# import torch.nn.functional as F
#
#
# logger = logging.getLogger(__name__)
#
#
# class GradientReversalLayer(torch.autograd.Function):
# """
# Implement the gradient reversal layer for the convenience of domain adaptation neural network.
# The forward part is the identity function while the backward part is the negative function.
# """
# @staticmethod
# def forward(self, inputs):
# return inputs
# @staticmethod
# def backward(self, grad_output):
# grad_input = grad_output.clone()
# grad_input = -grad_input
# return grad_input
#
#
# class MDANet(nn.Module):
# """
# Multi-layer perceptron with adversarial regularizer by domain classification.
# """
# def __init__(self, configs):
# super(MDANet, self).__init__()
# self.input_dim = configs["input_dim"]
# self.num_hidden_layers = len(configs["hidden_layers"])
# self.num_neurons = [self.input_dim] + configs["hidden_layers"]
# self.num_domains = configs["num_domains"]
# # Parameters of hidden, fully-connected layers, feature learning component.
# self.hiddens = nn.ModuleList([nn.Linear(self.num_neurons[i], self.num_neurons[i+1])
# for i in range(self.num_hidden_layers)])
# # Parameter of the final softmax classification layer.
# self.softmax = nn.Linear(self.num_neurons[-1], 1)
# # Parameter of the domain classification layer, multiple sources single target domain adaptation.
# self.domains = nn.ModuleList([nn.Linear(self.num_neurons[-1], 1) for _ in range(self.num_domains)])
# # Gradient reversal layer.
# self.grls = [GradientReversalLayer() for _ in range(self.num_domains)]
# #self.cel = nn.CrossEntropyLoss()
# self.cel = nn.MSELoss()
#
# def forward(self, sinputs, tinputs):
# """
# :param sinputs: A list of k inputs from k source domains.
# :param tinputs: Input from the target domain.
# :return:
# """
# sh_relu, th_relu = sinputs, tinputs
# for i in range(self.num_domains):
# for hidden in self.hiddens:
# sh_relu[i] = F.relu(hidden(sh_relu[i]))
# for hidden in self.hiddens:
# th_relu = F.relu(hidden(th_relu))
# # sh_relu = F.relu(hidden(sh_relu))
# # Classification probabilities on k source domains.
# logprobs = []
# for i in range(self.num_domains):
# logprobs.append(F.log_softmax(self.softmax(sh_relu[i]), dtype=torch.float32, dim=1))
# logprobs.append(self.softmax(sh_relu[i]))
# # logprobs.append(sh_relu[i])
#
# # Domain classification accuracies.
# sdomains, tdomains = [], []
# for i in range(self.num_domains):
# # sdomains.append(F.log_softmax(self.domains[i](self.grls[i].apply(sh_relu[i])), dim=1))
# # tdomains.append(F.log_softmax(self.domains[i](self.grls[i].apply(th_relu)), dim=1))
# sdomains.append(F.log_softmax(self.domains[i](self.grls[i].apply(sh_relu[i])), dim=0))
# tdomains.append(F.log_softmax(self.domains[i](self.grls[i].apply(th_relu)), dim=0))
# return logprobs, sdomains, tdomains
#
# def inference(self, inputs):
# h_relu = inputs
# for hidden in self.hiddens:
# h_relu = F.relu(hidden(h_relu))
# # Classification probability.
# #logprobs = F.log_softmax(self.softmax(h_relu), dim=1)
# logprobs = self.softmax(h_relu)
# return logprobs
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
logger = logging.getLogger(__name__)
class GradientReversalLayer(torch.autograd.Function):
"""
Implement the gradient reversal layer for the convenience of domain adaptation neural network.
The forward part is the identity function while the backward part is the negative function.
"""
@staticmethod
def forward(self, inputs):
return inputs
@staticmethod
def backward(self, grad_output):
grad_input = grad_output.clone()
grad_input = -grad_input
return grad_input
class MDANet(nn.Module):
"""
Multi-layer perceptron with adversarial regularizer by domain classification.
"""
def __init__(self, configs):
super(MDANet, self).__init__()
self.input_dim = configs["input_dim"]
self.num_hidden_layers = len(configs["hidden_layers"])
self.num_neurons = [self.input_dim] + configs["hidden_layers"]
self.num_domains = configs["num_domains"]
# Parameters of hidden, fully-connected layers, feature learning component.
self.hiddens = nn.ModuleList([nn.Linear(self.num_neurons[i], self.num_neurons[i + 1])
for i in range(self.num_hidden_layers)])
# Parameter of the final softmax classification layer.
self.softmax = nn.Linear(self.num_neurons[-1], 1)
# Parameter of the domain classification layer, multiple sources single target domain adaptation.
self.domains = nn.ModuleList([nn.Linear(self.num_neurons[-1], 1) for _ in range(self.num_domains)])
# Gradient reversal layer.
self.grls = [GradientReversalLayer() for _ in range(self.num_domains)]
def forward(self, sinputs, tinputs):
"""
:param sinputs: A list of k inputs from k source domains.
:param tinputs: Input from the target domain.
:return:
"""
sh_relu, th_relu = sinputs, tinputs
for i in range(self.num_domains):
for hidden in self.hiddens:
sh_relu[i] = F.relu(hidden(sh_relu[i]))
for hidden in self.hiddens:
th_relu = F.relu(hidden(th_relu))
# Classification probabilities on k source domains.
logprobs = []
for i in range(self.num_domains):
#logprobs.append(F.log_softmax(self.softmax(sh_relu[i]), dim=0))
logprobs.append(F.softmax(self.softmax(sh_relu[i]), dim=0))
# Domain classification accuracies.
sdomains, tdomains = [], []
for i in range(self.num_domains):
#sdomains.append(F.log_softmax(self.domains[i](self.grls[i].apply(sh_relu[i])), dim=0))
#tdomains.append(F.log_softmax(self.domains[i](self.grls[i].apply(th_relu)), dim=0))
sdomains.append(F.softmax(self.domains[i](self.grls[i].apply(sh_relu[i])), dim=0))
tdomains.append(F.softmax(self.domains[i](self.grls[i].apply(th_relu)), dim=0))
return logprobs, sdomains, tdomains
def inference(self, inputs):
h_relu = inputs
for hidden in self.hiddens:
h_relu = F.relu(hidden(h_relu))
# Classification probability.
logprobs = F.log_softmax(self.softmax(h_relu), dim=0)
return logprobs
# preds = F.softmax(self.softmax(h_relu), dim=0)
# return preds