-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupperbound.py
218 lines (171 loc) · 10.1 KB
/
upperbound.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
from __future__ import print_function
from NeuralNetwork import *
from DataSet import *
from CompetitiveMCTS import *
from CooperativeMCTS import *
def upperbound(dataSetName, bound, tau, gameType, image_index, eta, wbits, abits, nameFile, seed):
outF = open("results/" + nameFile, "w+")
MCTS_all_maximal_time = 500
NN = NeuralNetwork(dataSetName, abits, wbits, 'full-qnn', seed)
NN.train_network_QNN()
print("Dataset is %s." % NN.data_set)
dataset = DataSet(dataSetName, 'testing')
realLabel = dataset.get_True_Label(image_index)
image = dataset.get_input(image_index)
(label, confident) = NN.predict(image)
predicted = NN.get_label(int(label))
print("Prediction on input with index %s, whose class predicted is '%s' (true value %s ) and the confidence is %s."
% (image_index, predicted, NN.get_label(int(realLabel)), confident))
outF.write(
"Prediction on input with index %s, whose class predicted is '%s' (true value %s ) and the confidence is %s.\n"
% (image_index, predicted, NN.get_label(int(realLabel)), confident))
print("the second player is %s." % gameType)
outF.write("the second player is %s.\n" % gameType)
if not predicted == NN.get_label(int(realLabel)):
print("NN misclassification without attack")
outF.write("NN misclassification without attack")
exit(0)
outF.flush()
# choose between "cooperative" and "competitive"
if gameType == 'cooperative':
mctsInstance = MCTSCooperative(dataSetName, NN, image_index, image, tau, eta) # , target_class)
mctsInstance.initialiseMoves()
start_time_all = time.time()
runningTime_all = 0
currentBest = eta[1]
times = {}
number_of_current_bests = 0
while runningTime_all <= MCTS_all_maximal_time:
print("Time: " + str(runningTime_all))
# Here are three steps for MCTS
(leafNode, availableActions) = mctsInstance.treeTraversal(mctsInstance.rootIndex)
newNodes = mctsInstance.initialiseExplorationNode(leafNode, availableActions)
for node in newNodes:
(_, value) = mctsInstance.sampling(node, availableActions)
mctsInstance.backPropagation(node, value)
if currentBest > mctsInstance.bestCase[0]:
print("best distance up to now is %s" % (str(mctsInstance.bestCase[0])))
currentBest = mctsInstance.bestCase[0]
times[number_of_current_bests] = time.time() - start_time_all
number_of_current_bests += 1
# store the current best
(_, bestManipulation) = mctsInstance.bestCase
image1 = mctsInstance.applyManipulation(bestManipulation)
path0 = "%s_pic/%s_currentBest.png" % (dataSetName, image_index)
NN.save_input(image1, path0)
runningTime_all = time.time() - start_time_all
(_, bestManipulation) = mctsInstance.bestCase
print("the number of sampling: %s" % mctsInstance.numOfSampling)
print("the number of adversarial examples: %s\n" % mctsInstance.numAdv)
image1 = mctsInstance.applyManipulation(bestManipulation)
(newClass, newConfident) = NN.predict(image1)
newClassStr = NN.get_label(int(newClass))
if newClass != label: # and str(target_class)==str(NN.get_label(int(newClass))):
path0 = "%s_pic/%s_%s_modified_into_%s_with_confidence_%s.png" % (
dataSetName, image_index, NN.get_label(int(realLabel)), newClassStr, newConfident)
NN.save_input(image1, path0)
path0 = "%s_pic/%s_diff.png" % (dataSetName, image_index)
NN.save_input(np.absolute(image - image1), path0)
print("\nfound an adversary image within pre-specified bounded computational resource. "
"The following is its information: ")
outF.write("\nfound an adversary image within pre-specified bounded computational resource. "
"The following is its information: \n")
print("difference between images: %s" % (diffImage(image, image1)))
outF.write("difference between images: %s\n" % (diffImage(image, image1)))
print("number of adversarial examples found: %s\n" % mctsInstance.numAdv)
outF.write("number of adversarial examples found: %s\n" % mctsInstance.numAdv)
print("time needed to obtain an adversarial sample: \n")
outF.write("time needed to obtain an adversarial sample: \n")
for sample_index in range(0, number_of_current_bests):
output_line = str(sample_index) + ": " + str(times[sample_index]) + "\n"
print(output_line)
outF.write(output_line)
l2dist = l2Distance(mctsInstance.image, image1)
l1dist = l1Distance(mctsInstance.image, image1)
l0dist = l0Distance(mctsInstance.image, image1)
percent = diffPercent(mctsInstance.image, image1)
print("L2 distance %s" % l2dist)
outF.write("L2 distance %s\n" % l2dist)
print("L1 distance %s" % l1dist)
outF.write("L1 distance %s\n" % l1dist)
print("L0 distance %s" % l0dist)
outF.write("L0 distance %s\n" % l0dist)
print("manipulated percentage distance %s" % percent)
outF.write("manipulated percentage distance %s\n" % percent)
print("class is changed into '%s' with confidence %s\n" % (newClassStr, newConfident))
outF.write("class is changed into '%s' with confidence %s\n" % (newClassStr, newConfident))
outF.flush()
outF.close()
return time.time() - start_time_all, newConfident, percent, l2dist, l1dist, l0dist, 0
else:
print("\nfailed to find an adversary image within pre-specified bounded computational resource. ")
outF.write("\nfailed to find an adversary image within pre-specified bounded computational resource. \n")
outF.flush()
outF.close()
return 0, 0, 0, 0, 0, 0, 0
elif gameType == 'competitive':
mctsInstance = MCTSCompetitive(dataSetName, NN, image_index, image, tau, eta)
mctsInstance.initialiseMoves()
start_time_all = time.time()
runningTime_all = 0
currentBest = eta[1]
currentBestIndex = 0
while runningTime_all <= MCTS_all_maximal_time:
(leafNode, availableActions) = mctsInstance.treeTraversal(mctsInstance.rootIndex)
newNodes = mctsInstance.initialiseExplorationNode(leafNode, availableActions)
for node in newNodes:
(_, value) = mctsInstance.sampling(node, availableActions)
mctsInstance.backPropagation(node, value)
if currentBest > mctsInstance.bestCase[0]:
print("best distance up to now is %s" % (str(mctsInstance.bestCase[0])))
currentBest = mctsInstance.bestCase[0]
currentBestIndex += 1
# store the current best
(_, bestManipulation) = mctsInstance.bestCase
image1 = mctsInstance.applyManipulation(bestManipulation)
path0 = "%s_pic/%s_currentBest_%s.png" % (dataSetName, image_index, currentBestIndex)
NN.save_input(image1, path0)
runningTime_all = time.time() - start_time_all
(bestValue, bestManipulation) = mctsInstance.bestCase
print("the number of sampling: %s" % mctsInstance.numOfSampling)
print("the number of adversarial examples: %s\n" % mctsInstance.numAdv)
print("the number of max features is %s" % mctsInstance.bestFeatures()[0])
maxfeatures = mctsInstance.bestFeatures()[0]
if bestValue < eta[1]:
image1 = mctsInstance.applyManipulation(bestManipulation)
(newClass, newConfident) = NN.predict(image1)
newClassStr = NN.get_label(int(newClass))
if newClass != label:
path0 = "%s_pic/%s_%s_modified_into_%s_with_confidence_%s.png" % (
dataSetName, image_index, NN.get_label(int(realLabel)), newClassStr, newConfident)
NN.save_input(image1, path0)
path0 = "%s_pic/%s_diff.png" % (dataSetName, image_index)
NN.save_input(np.absolute(image - image1), path0)
print("\nfound an adversary image within pre-specified bounded computational resource. "
"The following is its information: ")
print("difference between images: %s" % (diffImage(image, image1)))
print("number of adversarial examples found: %s" % mctsInstance.numAdv)
l2dist = l2Distance(mctsInstance.image, image1)
l1dist = l1Distance(mctsInstance.image, image1)
l0dist = l0Distance(mctsInstance.image, image1)
percent = diffPercent(mctsInstance.image, image1)
print("L2 distance %s" % l2dist)
print("L1 distance %s" % l1dist)
print("L0 distance %s" % l0dist)
print("manipulated percentage distance %s" % percent)
print("class is changed into '%s' with confidence %s\n" % (newClassStr, newConfident))
return time.time() - start_time_all, newConfident, percent, l2dist, l1dist, l0dist, maxfeatures
else:
print("\nthe robustness of the (input, model) is under control, "
"with the first player is able to defeat the second player "
"who aims to find adversarial example by "
"playing suitable strategies on selecting features. ")
return 0, 0, 0, 0, 0, 0, 0
else:
print("\nthe robustness of the (input, model) is under control, "
"with the first player is able to defeat the second player "
"who aims to find adversarial example by "
"playing suitable strategies on selecting features. ")
return 0, 0, 0, 0, 0, 0, 0
else:
print("Unrecognised game type. Try 'cooperative' or 'competitive'.")