forked from cfchen-duke/ProtoPNet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelpers.py
45 lines (40 loc) · 1.3 KB
/
helpers.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
import os
import torch
import numpy as np
def list_of_distances(X, Y):
return torch.sum((torch.unsqueeze(X, dim=2) - torch.unsqueeze(Y.t(), dim=0)) ** 2, dim=1)
def make_one_hot(target, target_one_hot):
target = target.view(-1,1)
target_one_hot.zero_()
target_one_hot.scatter_(dim=1, index=target, value=1.)
def makedir(path):
'''
if path does not exist in the file system, create it
'''
if not os.path.exists(path):
os.makedirs(path)
def print_and_write(str, file):
print(str)
file.write(str + '\n')
def find_high_activation_crop(activation_map, percentile=95):
threshold = np.percentile(activation_map, percentile)
mask = np.ones(activation_map.shape)
mask[activation_map < threshold] = 0
lower_y, upper_y, lower_x, upper_x = 0, 0, 0, 0
for i in range(mask.shape[0]):
if np.amax(mask[i]) > 0.5:
lower_y = i
break
for i in reversed(range(mask.shape[0])):
if np.amax(mask[i]) > 0.5:
upper_y = i
break
for j in range(mask.shape[1]):
if np.amax(mask[:,j]) > 0.5:
lower_x = j
break
for j in reversed(range(mask.shape[1])):
if np.amax(mask[:,j]) > 0.5:
upper_x = j
break
return lower_y, upper_y+1, lower_x, upper_x+1