forked from max-andr/square-attack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
38 lines (29 loc) · 1.02 KB
/
utils.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
import numpy as np
import os
class Logger:
def __init__(self, path):
self.path = path
if path != '':
folder = '/'.join(path.split('/')[:-1])
if not os.path.exists(folder):
os.makedirs(folder)
def print(self, message):
print(message)
if self.path != '':
with open(self.path, 'a') as f:
f.write(message + '\n')
f.flush()
def dense_to_onehot(y_test, n_cls):
y_test_onehot = np.zeros([len(y_test), n_cls], dtype=bool)
y_test_onehot[np.arange(len(y_test)), y_test] = True
return y_test_onehot
def random_classes_except_current(y_test, n_cls):
y_test_new = np.zeros_like(y_test)
for i_img in range(y_test.shape[0]):
lst_classes = list(range(n_cls))
lst_classes.remove(y_test[i_img])
y_test_new[i_img] = np.random.choice(lst_classes)
return y_test_new
def softmax(x):
e_x = np.exp(x - np.max(x, axis=1, keepdims=True))
return e_x / e_x.sum(axis=1, keepdims=True)