-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgiw.py
240 lines (186 loc) · 8.36 KB
/
giw.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import os
import os.path
import torch
from torch.utils.data import TensorDataset
import torchvision.transforms as transforms
import random
import argparse
from tqdm import tqdm
import matplotlib.pyplot as plt
from dataloader import ColorMNIST
from model import Net
from kmm import kmm
from utils import *
parser = argparse.ArgumentParser()
parser.add_argument('--lr', type=float, default=0.0005, help='learning rate')
parser.add_argument('--step', type=float, default=100, help='period of learning rate decay')
parser.add_argument('--gamma', type=float, default=0.1, help='multiplicative factor of learning rate decay')
parser.add_argument('--wd', type=float, default=0.002, help='weight decay')
parser.add_argument('--bs', type=int, default=256, help='batch size for training data')
parser.add_argument('--num_epoch', type=int, default=400, help='total number of training epoch')
parser.add_argument('--seed', type=int, default=99, help='random seed')
args = parser.parse_args()
def set_seed(seed=args.seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
def build_model():
net = Net()
if torch.cuda.is_available():
net.cuda()
opt = torch.optim.Adam(net.parameters(), lr=args.lr, weight_decay=args.wd)
scheduler = torch.optim.lr_scheduler.StepLR(opt, step_size=args.step, gamma=args.gamma)
return net, opt, scheduler
def to_cuda(x):
if torch.cuda.is_available():
x = x.cuda()
return x
def main():
set_seed(args.seed)
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Resize((32, 32))
])
train_dataset = ColorMNIST(root='./data/',
download=True,
train=True,
val=False,
transform=transform
)
test_dataset = ColorMNIST(root='./data/',
download=True,
train=False,
transform=transform
)
val_dataset = ColorMNIST(root='./data/',
download=True,
train=True,
val=True,
transform=transform
)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=args.bs,
num_workers=0,
drop_last=False,
shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=args.bs,
num_workers=0,
drop_last=False,
shuffle=False)
val_loader = torch.utils.data.DataLoader(dataset=val_dataset,
batch_size=args.bs,
num_workers=0,
drop_last=False,
shuffle=True)
# define the model, optimizer, and lr decay scheduler
net, opt, scheduler = build_model()
print("pre-training starts")
# pre-train the model
for epoch in tqdm(range(10)):
test_acc_tmp = []
for i, (image, labels, _) in enumerate(train_loader):
net.train()
image, labels = to_cuda(image), to_cuda(labels)
out_train = net(image)
l_tr = F.cross_entropy(out_train, labels.squeeze())
opt.zero_grad()
l_tr.backward()
opt.step()
net.eval()
# test acc
for itr, (test_img, test_label, __) in enumerate(test_loader):
test_img, test_label = to_cuda(test_img), to_cuda(test_label)
test_correct = 0
test_total = 0
out_test = net(test_img)
_, predicted = torch.max(out_test.data, 1)
test_total += test_label.size(0)
test_correct += (predicted == test_label.squeeze()).sum().item()
test_accuracy = test_correct / test_total
test_acc_tmp.append(test_accuracy)
test_accuracy_mean = np.mean(test_acc_tmp)
print("test accuracy mean is", test_accuracy_mean)
# retrieve transformed features & estimate alpha
net.fc1.register_forward_hook(get_activation('fc1'))
fe_tr, fe_val, index_val = get_feature(net, train_loader, val_loader)
print("training osvm starts")
val_dic, alpha = val_split(fe_tr, fe_val, index_val)
print("alpha is estimated as", alpha)
# train the model
test_acc = []
for epoch in tqdm(range(args.num_epoch)):
train_acc_tmp = []
test_acc_tmp = []
for i, (image, labels, _) in enumerate(train_loader):
# weight estimation (we) step
net.cuda()
net.eval()
image, labels = to_cuda(image), to_cuda(labels)
out_train = net(image)
l_tr = F.cross_entropy(out_train, labels.squeeze(), reduction='none').reshape(-1, 1)
val_image, val_labels, val__ = next(iter(val_loader))
val_image, val_labels = to_cuda(val_image), to_cuda(val_labels)
split_labels = [bool(val_dic[i.item()]) for i in val__]
val1_image, val1_labels = val_image[split_labels], val_labels[split_labels]
val2_image, val2_labels = val_image[np.invert(split_labels)], val_labels[np.invert(split_labels)]
out_val1 = net(val1_image)
l_val1 = F.cross_entropy(out_val1, val1_labels.squeeze(), reduction='none').reshape(-1, 1)
n_batch = len(_)
dist = torch.cdist(l_tr, l_tr)[torch.tril_indices(n_batch, n_batch, offset=-1).unbind()]
kernel_width = torch.quantile(dist, q=0.5).item()
l_tr_cpu, l_val_cpu = np.array(l_tr.detach().cpu()), np.array(l_val1.detach().cpu())
coef = kmm(l_tr_cpu, l_val_cpu, kernel_width)
w = torch.from_numpy(np.asarray(coef)).float().cuda()
w = (w / w.sum()) * n_batch
# weighted classification (wc) step
net.train()
out_train_wc = net(image)
l_tr_wc = F.cross_entropy(out_train_wc, labels.squeeze(), reduction='none')
l_tr_wc_weighted = torch.mean(l_tr_wc * w)
out_val2 = net(val2_image)
l_val2 = F.cross_entropy(out_val2, val2_labels.squeeze())
l_total = alpha * l_tr_wc_weighted + (1 - alpha) * l_val2
opt.zero_grad()
l_total.backward()
opt.step()
# train acc
train_correct = 0
train_total = 0
_, predicted = torch.max(out_train_wc.data, 1)
train_total += labels.size(0)
train_correct += (predicted == labels.squeeze()).sum().item()
train_accuracy = train_correct / train_total
train_acc_tmp.append(train_accuracy)
train_accuracy_mean = np.mean(train_acc_tmp)
print("train accuracy mean is", train_accuracy_mean)
net.eval()
# test acc
for itr, (test_img, test_label, __) in enumerate(test_loader):
test_img, test_label = to_cuda(test_img), to_cuda(test_label)
test_correct = 0
test_total = 0
out_test = net(test_img)
_, predicted = torch.max(out_test.data, 1)
test_total += test_label.size(0)
test_correct += (predicted == test_label.squeeze()).sum().item()
test_accuracy = test_correct / test_total
test_acc_tmp.append(test_accuracy)
test_accuracy_mean = np.mean(test_acc_tmp)
print("test accuracy mean is", test_accuracy_mean)
test_acc.append(test_accuracy_mean)
test_acc_arr = np.array(test_acc)
scheduler.step()
# save the output
np.savetxt('./output/test_acc.txt', test_acc_arr, fmt='%s')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(test_acc)
fig.savefig('./output/test_acc.png')
if __name__ == '__main__':
main()