forked from cmhcbb/attackbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
72 lines (61 loc) · 2.46 KB
/
models.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
import torch
import numpy as np
from torch.autograd import Variable
class PytorchModel(object):
def __init__(self,model, bounds, num_classes):
self.model = model
self.model.eval()
self.bounds = bounds
self.num_classes = num_classes
self.num_queries = 0
def predict(self,image):
image = torch.clamp(image,self.bounds[0],self.bounds[1]).cuda()
if len(image.size())!=4:
image = image.unsqueeze(0)
output = self.model(image)
self.num_queries += 1
return output
def predict_prob(self,image):
with torch.no_grad():
image = torch.clamp(image,self.bounds[0],self.bounds[1]).cuda()
if len(image.size())!=4:
image = image.unsqueeze(0)
output = self.model(image)
self.num_queries += image.size(0)
return output
def predict_label(self, image, batch=False):
if isinstance(image, np.ndarray):
image = torch.from_numpy(image).type(torch.FloatTensor)
image = torch.clamp(image,self.bounds[0],self.bounds[1]).cuda()
if len(image.size())!=4:
image = image.unsqueeze(0)
#image = Variable(image, volatile=True) # ?? not supported by latest pytorch
with torch.no_grad():
output = self.model(image)
self.num_queries += image.size(0)
#image = Variable(image, volatile=True) # ?? not supported by latest pytorch
_, predict = torch.max(output.data, 1)
if batch:
return predict
else:
return predict[0]
def predict_ensemble(self, image):
if isinstance(image, np.ndarray):
image = torch.from_numpy(image).type(torch.FloatTensor)
image = torch.clamp(image,self.bounds[0],self.bounds[1]).cuda()
if len(image.size())!=4:
image = image.unsqueeze(0)
with torch.no_grad():
output = self.model(image)
output.zero_()
for i in range(10):
output += self.model(image)
self.num_queries += image.size(0)
_, predict = torch.max(output.data, 1)
return predict[0]
def get_num_queries(self):
return self.num_queries
#def get_infor_hard(self, dis_history, query_history):
# return torch.mean(dis_history,2,keepdim=True), torch.mean(query_history,2,keepdim=True)
def get_gradient(self,loss):
loss.backward()