-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
executable file
·210 lines (167 loc) · 7.86 KB
/
main.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
#!/usr/bin/env python
"""
main file
author: Xiaowei Huang
"""
import sys
sys.path.append('networks')
sys.path.append('safety_check')
sys.path.append('configuration')
import time
import numpy as np
import copy
import random
# import matplotlib.pyplot as plt
from loadData import loadData
from regionSynth import regionSynth, initialiseRegion
from precisionSynth import precisionSynth
from safety_analysis import safety_analysis
from configuration import *
from basics import *
from networkBasics import *
from searchTree import searchTree
from dataCollection import dataCollection
def main():
model = loadData()
dc = dataCollection()
# handle a set of inputs starting from an index
if dataProcessing == "batch":
for whichIndex in range(startIndexOfImage,startIndexOfImage + dataProcessingBatchNum):
print "\n\nprocessing input of index %s in the dataset: " %(str(whichIndex))
if task == "safety_check":
handleOne(model,dc,whichIndex)
# handle a sinextNumSpane input
else:
print "\n\nprocessing input of index %s in the dataset: " %(str(startIndexOfImage))
if task == "safety_check":
handleOne(model,dc,startIndexOfImage)
if dataProcessing == "batch":
dc.provideDetails()
dc.summarise()
dc.close()
###########################################################################
#
# safety checking
# starting from the first hidden layer
#
############################################################################
def handleOne(model,dc,startIndexOfImage):
# get an image to interpolate
global np
image = NN.getImage(model,startIndexOfImage)
print("the shape of the input is "+ str(image.shape))
#image = np.array([3.58747339,1.11101673])
dc.initialiseIndex(startIndexOfImage)
if checkingMode == "stepwise":
k = startLayer
elif checkingMode == "specificLayer":
k = maxLayer
while k <= maxLayer:
layerType = getLayerType(model, k)
start_time = time.time()
# only these layers need to be checked
if layerType in ["Convolution2D", "Dense"]:
dc.initialiseLayer(k)
# initialise a search tree
st = searchTree(image,k)
st.addImages(model,[image])
print "\nstart checking the safety of layer "+str(k)
print "the current context is %s"%(st.numSpans)
(originalClass,originalConfident) = NN.predictWithImage(model,image)
origClassStr = dataBasics.LABELS(int(originalClass))
path0="%s/%s_original_as_%s_with_confidence_%s.png"%(directory_pic_string,startIndexOfImage,origClassStr,originalConfident)
dataBasics.save(-1,image, path0)
# for every layer
f = 0
if numOfPointsAfterEachFeature == 1:
testNum = numOfFeatures
else: testNum = (numOfPointsAfterEachFeature ** (n+1)) / (numOfPointsAfterEachFeature - 1)
while f <= testNum:
f += 1
index = st.getOneUnexplored()
imageIndex = copy.deepcopy(index)
howfar = st.getHowFar(index[0],0)
print "\nhow far is the current image from the original one: %s"%(howfar)
# for every image
# start from the first hidden layer
t = 0
while True:
print "current index: %s current layer: %s"%(str(index),t)
# print "current layer: %s."%(t)
print "how many dimensions have been changed: %s."%(len(st.manipulated[-1]))
# pick the first element of the queue
# print "1) get a manipulated input ..."
(image0,span,numSpan,numDimsToMani) = st.getInfo(index)
path2 = directory_pic_string+"/temp.png"
# print " saved into %s"%(path2)
dataBasics.save(index[0],image0,path2)
# print "2) synthesise region ..."
# ne: next region, i.e., e_{k+1}
(nextSpan,nextNumSpan,numDimsToMani) = regionSynth(model,dataset,image0,st.manipulated[t],t,span,numSpan,numDimsToMani)
st.addManipulated(t,nextSpan.keys())
#print "3) synthesise precision ..."
#if not found == True: nextNumSpan = dict(map(lambda (k,v): (k, abs(v-1)), nextNumSpan.iteritems()))
# np : next precision, i.e., p_{k+1}
#np = precisionSynth(model,dataset,image0,t,span,numSpan,nextSpan,nextNumSpan,cp)
(nextSpan,nextNumSpan,np) = precisionSynth(t,nextSpan,nextNumSpan)
#print "the precision is %s."%(np)
print "dimensions to be considered: %s"%(nextSpan)
#print "dimensions that have been considered before: %s"%(st.manipulated[t])
print "spans for the dimensions: %s"%(nextNumSpan)
if t == k:
# print "3) safety analysis ..."
# wk for the set of counterexamples
# rk for the set of images that need to be considered in the next precision
# rs remembers how many input images have been processed in the last round
# nextSpan and nextNumSpan are revised by considering the precision np
(nextSpan,nextNumSpan,rs,wk,rk) = safety_analysis(model,dataset,t,startIndexOfImage,st,index,nextSpan,nextNumSpan,np)
print "4) add new images ..."
random.seed(time.time())
if len(rk) > numOfPointsAfterEachFeature:
rk = random.sample(rk, numOfPointsAfterEachFeature)
diffs = diffImage(image0,rk[0])
print("the dimensions of the images that are changed in the previous round: %s"%diffs)
if len(diffs) == 0: st.clearManipulated(k)
st.addImages(model,rk)
st.removeProcessed(imageIndex)
(re,percent,eudist) = reportInfo(image,rs,wk,numDimsToMani,howfar,image0)
break
else:
print "3) add new intermediate node ..."
index = st.addIntermediateNode(image0,nextSpan,nextNumSpan,np,numDimsToMani,index)
re = False
t += 1
if re == True:
dc.addManipulationPercentage(percent)
dc.addEuclideanDistance(eudist)
(ocl,ocf) = NN.predictWithImage(model,rk[0])
dc.addConfidence(ocf)
break
st.destructor()
runningTime = time.time() - start_time
dc.addRunningTime(runningTime)
if re == True and exitWhen == "foundFirst":
break
k += 1
print("Please refer to the file %s for statistics."%(dc.fileName))
def reportInfo(image,rs,wk,numDimsToMani,howfar,image0):
# exit only when we find an adversarial example
if wk == []:
print "no adversarial example is found in this layer."
return (False,0,0)
else:
print "an adversarial example has been found."
diffs = diffImage(image,image0)
eudist = euclideanDistance(image,image0)
elts = len(diffs.keys())
if len(image0.shape) == 2:
percent = elts / float(len(image0)*len(image0[0]))
elif len(image0.shape) == 1:
percent = elts / float(len(image0))
elif len(image0.shape) == 3:
percent = elts / float(len(image0)*len(image0[0])*len(image0[0][0]))
return (True,percent,eudist)
if __name__ == "__main__":
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))