-
Notifications
You must be signed in to change notification settings - Fork 9
/
abmil.py
194 lines (164 loc) · 6.77 KB
/
abmil.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
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class Attention(nn.Module):
def __init__(self, in_size, out_size, confounder_path=False, confounder_learn=False, \
confounder_dim=128, confounder_merge='cat'):
super(Attention, self).__init__()
self.L = in_size
self.D = in_size
self.K = 1
self.confounder_merge = confounder_merge
assert confounder_merge in ['cat', 'add', 'sub']
# self.feature_extractor_part1 = nn.Sequential(
# nn.Conv2d(1, 20, kernel_size=5),
# nn.ReLU(),
# nn.MaxPool2d(2, stride=2),
# nn.Conv2d(20, 50, kernel_size=5),
# nn.ReLU(),
# nn.MaxPool2d(2, stride=2)
# )
# self.feature_extractor_part2 = nn.Sequential(
# nn.Linear(50 * 4 * 4, self.L),
# nn.ReLU(),
# )
# self.attention_1 = nn.Sequential(
# nn.Linear(self.L, self.D),
# nn.Tanh(),
# )
# self.attention_1 = nn.Identity()
# self.attention_2 = nn.Linear(self.D, self.K)
self.attention = nn.Sequential(
nn.Linear(self.L, self.D),
nn.Tanh(),
nn.Linear(self.D, self.K)
)
self.classifier = nn.Linear(self.L*self.K, out_size)
self.confounder_path=None
if confounder_path:
print('deconfounding')
self.confounder_path = confounder_path
conf_list = []
for i in confounder_path:
conf_list.append(torch.from_numpy(np.load(i)).view(-1,in_size).float())
conf_tensor = torch.cat(conf_list, 0)
conf_tensor_dim = conf_tensor.shape[-1]
if confounder_learn:
self.confounder_feat = nn.Parameter(conf_tensor, requires_grad=True)
else:
self.register_buffer("confounder_feat",conf_tensor)
joint_space_dim = confounder_dim
dropout_v = 0.5
# self.confounder_W_q = nn.Linear(in_size, joint_space_dim)
# self.confounder_W_k = nn.Linear(conf_tensor_dim, joint_space_dim)
self.W_q = nn.Linear(in_size, joint_space_dim)
self.W_k = nn.Linear(conf_tensor_dim, joint_space_dim)
if confounder_merge == 'cat':
self.classifier = nn.Linear(self.L*self.K+conf_tensor_dim, out_size)
elif confounder_merge == 'add' or 'sub':
self.classifier = nn.Linear(self.L*self.K, out_size)
self.dropout = nn.Dropout(dropout_v)
def forward(self, x):
# x = x.squeeze(0)
# H = self.feature_extractor_part1(x)
# H = H.view(-1, 50 * 4 * 4)
# H = self.feature_extractor_part2(H) # NxL
# A = self.attention_1(x)
# A = self.attention_2(A) # NxK
A = self.attention(x) # NxK
A = torch.transpose(A, 1, 0) # KxN
A = F.softmax(A, dim=1) # softmax over N
# print('norm')
# A = F.softmax(A/ torch.sqrt(torch.tensor(x.shape[1])), dim=1) # For Vis
M = torch.mm(A, x) # KxL
if self.confounder_path:
device = M.device
# bag_q = self.confounder_W_q(M)
# conf_k = self.confounder_W_k(self.confounder_feat)
bag_q = self.W_q(M)
conf_k = self.W_k(self.confounder_feat)
deconf_A = torch.mm(conf_k, bag_q.transpose(0, 1))
deconf_A = F.softmax( deconf_A / torch.sqrt(torch.tensor(conf_k.shape[1], dtype=torch.float32, device=device)), 0) # normalize attention scores, A in shape N x C,
conf_feats = torch.mm(deconf_A.transpose(0, 1), self.confounder_feat) # compute bag representation, B in shape C x V
if self.confounder_merge == 'cat':
M = torch.cat((M,conf_feats),dim=1)
elif self.confounder_merge == 'add':
M = M + conf_feats
elif self.confounder_merge == 'sub':
M = M - conf_feats
Y_prob = self.classifier(M)
Y_hat = torch.ge(Y_prob, 0.5).float()
if self.confounder_path:
return Y_prob, M, deconf_A
else:
return Y_prob, M, A
# AUXILIARY METHODS
def calculate_classification_error(self, X, Y):
Y = Y.float()
_, Y_hat, _ = self.forward(X)
error = 1. - Y_hat.eq(Y).cpu().float().mean().data.item()
return error, Y_hat
def calculate_objective(self, X, Y):
Y = Y.float()
Y_prob, _, A = self.forward(X)
Y_prob = torch.clamp(Y_prob, min=1e-5, max=1. - 1e-5)
neg_log_likelihood = -1. * (Y * torch.log(Y_prob) + (1. - Y) * torch.log(1. - Y_prob)) # negative log bernoulli
return neg_log_likelihood, A
class GatedAttention(nn.Module):
def __init__(self):
super(GatedAttention, self).__init__()
self.L = 500
self.D = 128
self.K = 1
self.feature_extractor_part1 = nn.Sequential(
nn.Conv2d(1, 20, kernel_size=5),
nn.ReLU(),
nn.MaxPool2d(2, stride=2),
nn.Conv2d(20, 50, kernel_size=5),
nn.ReLU(),
nn.MaxPool2d(2, stride=2)
)
self.feature_extractor_part2 = nn.Sequential(
nn.Linear(50 * 4 * 4, self.L),
nn.ReLU(),
)
self.attention_V = nn.Sequential(
nn.Linear(self.L, self.D),
nn.Tanh()
)
self.attention_U = nn.Sequential(
nn.Linear(self.L, self.D),
nn.Sigmoid()
)
self.attention_weights = nn.Linear(self.D, self.K)
self.classifier = nn.Sequential(
nn.Linear(self.L*self.K, 1),
nn.Sigmoid()
)
def forward(self, x):
x = x.squeeze(0)
H = self.feature_extractor_part1(x)
H = H.view(-1, 50 * 4 * 4)
H = self.feature_extractor_part2(H) # NxL
A_V = self.attention_V(H) # NxD
A_U = self.attention_U(H) # NxD
A = self.attention_weights(A_V * A_U) # element wise multiplication # NxK
A = torch.transpose(A, 1, 0) # KxN
A = F.softmax(A, dim=1) # softmax over N
M = torch.mm(A, H) # KxL
Y_prob = self.classifier(M)
Y_hat = torch.ge(Y_prob, 0.5).float()
return Y_prob, Y_hat, A
# AUXILIARY METHODS
def calculate_classification_error(self, X, Y):
Y = Y.float()
_, Y_hat, _ = self.forward(X)
error = 1. - Y_hat.eq(Y).cpu().float().mean().item()
return error, Y_hat
def calculate_objective(self, X, Y):
Y = Y.float()
Y_prob, _, A = self.forward(X)
Y_prob = torch.clamp(Y_prob, min=1e-5, max=1. - 1e-5)
neg_log_likelihood = -1. * (Y * torch.log(Y_prob) + (1. - Y) * torch.log(1. - Y_prob)) # negative log bernoulli
return neg_log_likelihood, A