How to use _cdiff method in avocado

Best Python code snippet using avocado_python

attack.py

Source:attack.py Github

copy

Full Screen

1#!/usr/bin/env python32from matplotlib.patches import Circle3import matplotlib.pyplot as plt4import argparse5import os6import copy7import pandas as pd8import numpy as np9import tensorflow as tf1011os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'12from tensorflow.keras.models import load_model13#from keras.datasets import cifar1014import pickle15from scipy.optimize import dual_annealing # for local search 16# Helper functions17from differential_evolution import differential_evolution18#from scipy.optimize import differential_evolution19import helper202122class PixelAttacker:23 def __init__(self, models, data, class_names, dimensions=(224, 224)):24 # Load data and model25 self.models = models26 self.x_test, self.y_test = data27 self.class_names = class_names28 self.dimensions = dimensions29 # The below line is revised to keep the probabilities30 network_stats, correct_imgs, self.original_probability = helper.evaluate_models(self.models, self.x_test, self.y_test)31 self.correct_imgs = pd.DataFrame(correct_imgs, columns=['name', 'img', 'label', 'confidence', 'pred'])32 self.network_stats = pd.DataFrame(network_stats, columns=['name', 'accuracy', 'param_count'])3334 def predict_classes(self, xs, img, target_class, model, minimize=True):35 # Perturb the image with the given pixel(s) x and get the prediction of the model36 imgs_perturbed = helper.perturb_image(xs, img)37 predictions = model.predict(imgs_perturbed)[:, target_class]38 # This function should always be minimized, so return its complement if needed39 return predictions if minimize else 1 - predictions4041 def attack_success(self, x, img, target_class, model, targeted_attack=False, verbose=False, epsilon=0.5, no_stop=False):42 # Perturb the image with the given pixel(s) and get the prediction of the model43 attack_image = helper.perturb_image(x, img)4445 confidence = model.predict(attack_image)[0]46 predicted_class = np.argmax(confidence)4748 # If the prediction is what we want (misclassification or 49 # targeted classification), return True50 if verbose:51 print('Confidence:', confidence[target_class])52 if (confidence[target_class] <= epsilon and not no_stop and53 ((targeted_attack and predicted_class == target_class) or54 (not targeted_attack and predicted_class != target_class))):55 return True5657 def attack(self, img_id, model, target=None, pixel_count=1,58 maxiter=75, popsize=400, verbose=False, plot=False, DE='DE', epsilon=0.5, LS=0, no_stop=False):59 # Change the target class based on whether this is a targeted attack or not60 targeted_attack = target is not None61 target_class = target if targeted_attack else self.y_test[img_id, 0]6263 # Define bounds for a flat vector of x,y,r,g,b values64 # For more pixels, repeat this layout65 dim_x, dim_y = self.dimensions66 bounds = [(0, dim_x), (0, dim_y), (-1, 1), (-1, 1),(-1, 1)] * pixel_count6768 # Population multiplier, in terms of the size of the perturbation vector x69 popmul = max(1, popsize // len(bounds))7071 # Format the predict/callback functions for the differential evolution algorithm72 def predict_fn(xs):73 return self.predict_classes(xs, self.x_test[img_id], target_class, model, target is None)7475 def callback_fn(x, convergence):76 return self.attack_success(x, self.x_test[img_id], target_class, model, targeted_attack, verbose, epsilon=epsilon, no_stop=no_stop)7778 # Call Scipy's Implementation of Differential Evolution79 attack_result = differential_evolution(80 predict_fn, bounds, maxiter=maxiter, popsize=popmul,81 recombination=1, atol=-1, callback=callback_fn, polish=False, disp=True, DE=DE, LS=LS)82 83 # Calculate some useful statistics to return from this function84 attack_image = helper.perturb_image(attack_result.x, self.x_test[img_id])[0]85 prior_probs = model.predict(np.array([self.x_test[img_id]]))[0]86 predicted_probs = model.predict(np.array([attack_image]))[0]87 predicted_class = np.argmax(predicted_probs)88 actual_class = self.y_test[img_id, 0]89 success = predicted_probs[actual_class] < epsilon and (predicted_class != actual_class)90 cdiff = prior_probs[actual_class] - predicted_probs[actual_class]9192 # Show the best attempt at a solution (successful or not)93 if plot:94 helper.plot_image(attack_image, actual_class, self.class_names, predicted_class)9596 return [model.name, pixel_count, img_id, actual_class, predicted_class, success, cdiff, prior_probs,97 predicted_probs, attack_result.x]9899 def attack_all_least(self, models, samples=500, pixels=(64,), targeted=False,100 maxiter=75, popsize=400, verbose=False, DE='DE', epsilon=0.5, LS=0, no_stop=False):101 results = []102 target = None103 for model in models:104 model_results = []105 valid_imgs = self.correct_imgs[self.correct_imgs.name == model.name].img106 #img_samples = np.random.choice(valid_imgs, samples)107 img_samples = valid_imgs#[0:samples] ## revised by Yisong 2020.09.06, choose the first samples of images to attack108 #img_samples = valid_imgs * samples ## revised by Yisong 2020.08.29109110 for i, img in enumerate(img_samples):111 print(model.name, '- image', img, '-', i + 1, '/', len(img_samples))112 print('The original confidence: %f'%self.original_probability[i][self.y_test[i]])113 old_result = [] 114 pixel_count = pixels[0] # the up_pixel_count115 low_pixel_count = 0116 up_pixel_count = pixel_count117 fail_pixel_count = 0118 while(up_pixel_count - low_pixel_count > 1):119 print('The number of pixels is:', pixel_count)120 result = self.attack(img, model, target, pixel_count,121 maxiter=maxiter, popsize=popsize,122 verbose=verbose, DE=DE, epsilon=epsilon, LS=LS, no_stop=no_stop)123 if len(old_result)==0: 124 old_result = copy.copy(result)125 if not result[5]: break # fail with the most pixels126127 if result[5]: # success attack128 old_result = copy.copy(result)129 up_pixel_count = pixel_count130 else:131 low_pixel_count = pixel_count132133 pixel_count = int(low_pixel_count + (up_pixel_count - low_pixel_count)/2)134135 model_results.append(old_result)136 results += model_results137 helper.checkpoint(results, targeted)138 return results139140 def attack_all(self, models, samples=500, pixels=(1, 3, 5), targeted=False,141 maxiter=75, popsize=400, verbose=False, DE='DE', epsilon=0.5, LS=0, no_stop=False):142 results = []143 for model in models:144 model_results = []145 valid_imgs = self.correct_imgs[self.correct_imgs.name == model.name].img146 #img_samples = np.random.choice(valid_imgs, samples)147 img_samples = valid_imgs#[0:samples] ## revised by Yisong 2020.09.06, choose the first samples of images to attack148 #img_samples = valid_imgs * samples ## revised by Yisong 2020.08.29149150 for pixel_count in pixels:151 for i, img in enumerate(img_samples):152 print(model.name, '- image', img, '-', i + 1, '/', len(img_samples))153 targets = [None] if not targeted else range(10)154 print('The original confidence: %f'%self.original_probability[i][self.y_test[i]])155 for target in targets:156 if targeted:157 print('Attacking with target', self.class_names[target])158 if target == self.y_test[img, 0]:159 continue160 result = self.attack(img, model, target, pixel_count,161 maxiter=maxiter, popsize=popsize,162 verbose=verbose, DE=DE, epsilon=epsilon, LS=LS, no_stop=no_stop)163 model_results.append(result)164165 results += model_results166 helper.checkpoint(results, targeted)167 return results168169def ultra_attack(model, samples, target):170 ''' one-pixel attacking each sample in samples by reversing the point171 '''172 bounds = [(-1, 1), (-1, 1),(-1, 1)]173 limits = np.array(bounds, dtype='float').T 174 __scale_arg1 = 0.5 * (limits[0] + limits[1])175 __scale_arg2 = np.fabs(limits[0] - limits[1])176177 def _scale_parameters(trial):178 """179 scale from a number between 0 and 1 to parameters.180 """181 return __scale_arg1 + (trial - 0.5) * __scale_arg2182183 def _unscale_parameters(parameters):184 """185 scale from parameters to a number between 0 and 1.186 """187 return (parameters - __scale_arg1) / __scale_arg2 + 0.5188189 def _farmost(parameters):190 t = np.zeros((3))191 for i in range(3):192 if parameters[i] < 0: 193 t[i] = 1.194 else:195 t[i] = -1.196 return t197198 for i in range(len(samples)):199 print('starting attack the %d sample'%i)200 best_prob = 1.201 type = target[i]202 203 for x in range(224):204 for y in range(224):205 rgb = samples[i][x,y]206 samples[i][x,y] = _farmost(rgb) #_scale_parameters( 1.0 - _unscale_parameters(samples[i][x,y]) )207 prob = model.predict(samples[i].reshape(1,224,224,3))[0][type] 208 samples[i][x,y] = rgb209 if best_prob > prob: 210 best_prob, best_x, best_y, = prob, x, y 211 if best_prob < 0.5: break212 if best_prob < 0.5: break 213 print('best solution x=%d, y=%d with probability=%f'%(best_x,best_y, best_prob))214 print(samples[i][best_x,best_y])215216def get_IDs_RA(up, low, pdata,type=1, top_k=10):217# get the ids to do repeat attack218 _f = open(pdata,'rb')219 _data = pickle.load(_f)220 _f.close()221 IDs = [] 222 ## choise the top k cdiff 223 dlen = len(_data)224 t_data = np.zeros((dlen,4)) # to keep ID prior-conf attacked-conf cdiff225 for i in range(dlen):226 t_data[i][0], t_data[i][1], t_data[i][2], t_data[i][3] = _data[i][2], _data[i][7][type], _data[i][8][type], _data[i][6] 227 T_data = t_data[np.argsort(t_data[:,3])][ dlen - top_k:] 228 return T_data229230if __name__ == '__main__': 231 parser = argparse.ArgumentParser(description='Attack models on DR, CXR, DERM') 232 parser.add_argument('--source', default='dr', help='The source of being attacked[cxr/dr/derm].')233 parser.add_argument('--model', default='./model/dr/wb_model.h5', help='The trained model to be attacked.')234 parser.add_argument('--pixels', nargs='+', default=(1,), type=int,235 help='The number of pixels that can be perturbed.')236 parser.add_argument('--maxiter', default=35, type=int,237 help='The maximum number of iterations in the differential evolution algorithm before giving up and failing the attack.')238 parser.add_argument('--popsize', default=400, type=int,239 help='The number of adversarial images generated each iteration in the differential evolution algorithm. Increasing this number requires more computation.')240 parser.add_argument('--samples', default=8, type=int, 241 help='The number of image samples to attack. Images are sampled randomly from the dataset.')242 parser.add_argument('--targeted', action='store_true', help='Set this switch to test for targeted attacks.')243 parser.add_argument('--data', default='dr_pos_data_10.npy', help='The data file.')244 parser.add_argument('--type', default=1, type=int, help='The type of attacked samples, 0: negative, 1: positive.')245 parser.add_argument('--LP', action='store_true', help='Compute the least pixels to sucessfully attack.')246 parser.add_argument('--save', default='results.pkl', help='Save location for the results (pickle)')247 parser.add_argument('--DE', default='DE', help='The differential evolution algorithm: DE, SHADE, EBLSHADE.')248 parser.add_argument('--epsilon', default=0.5, type=float, help='The confidence threshold.')249 parser.add_argument('--no_stop', action='store_true', help='Do not stop when find a solution.')250 parser.add_argument('--LS', default=0, type=int, help='Do local searching: (0: no local search; 1: local search at the end; 2: local search at each better solution; 4: local search at each better solution and replace the best with the the new one if it is better than the last best one.).')251 parser.add_argument('--verbose', action='store_true', help='Print out additional information every iteration.')252253 # The following paremeters are for repeating attack 254 parser.add_argument('--RA', default=1, type=int, help='The repeating times of repeating attacks')255 parser.add_argument('--RAn', default=10, type=int, help='The number samples of repeating attack')256 parser.add_argument('--low', default=0.1, type=float, help='The confidence after first attack')257 parser.add_argument('--up', default=0.9, type=float, help='The confidence before first attack')258 parser.add_argument('--pickle', type=str, help='The results pickle file')259260 args = parser.parse_args() 261262 class_names = ['positive','negative']263 model = load_model('./model/'+args.source + '/wb_model.h5')264 true_label = np.load('./data/'+args.source + '/val_test_y.npy')265 predictions = np.load('./data/'+args.source +'/winning_model_preds.npy')266 data = np.load('./data/'+args.source + '/val_test_x_preprocess.npy')267 both_true = (true_label[:,args.type] >= 0.5) & (predictions[:,args.type] >= 0.5)268 if args.samples == -1 or args.samples > sum(both_true):269 args.samples = sum(both_true)270 test = data[both_true][0:args.samples], np.array([[args.type]]*args.samples)271272 if args.RA > 1:273 _ids = get_IDs_RA(args.up, args.low, 'results/' + args.source + '/' + args.pickle, args.type, top_k=args.RAn)274 _test = np.zeros((len(_ids),224,224,3)) 275 for i in range(min(len(_ids), args.RAn)): 276 print(_ids[i])277 _test[i] = test[0][ int(_ids[i][0]) ]278 test = _test, np.array([[args.type]] * len(_ids))279 RA_results = []280 attacker = PixelAttacker([model], test, class_names)281 for i in range(args.RA):282 results = attacker.attack_all([model], samples=len(_ids), pixels=args.pixels, targeted=args.targeted, \283 maxiter=args.maxiter, popsize=args.popsize, verbose=args.verbose, DE=args.DE, \284 epsilon=args.epsilon, LS=args.LS, no_stop=args.no_stop)285 RA_results += results286 columns = ['model', 'pixels', 'image', 'true', 'predicted', 'success', 'cdiff', 'prior_probs', 'predicted_probs', 'perturbation']287 results_table = pd.DataFrame(RA_results, columns=columns)288 print(results_table[['model', 'pixels', 'image', 'true', 'predicted', 'success']])289 print('Saving to', args.save)290 with open(args.save, 'wb') as file:291 pickle.dump(RA_results, file)292 293 ## draw the figures with annotated attack points294 # for each sample 295 for i in range(min(len(_ids), args.RAn)):296 _path = './results/' + args.source + '/'297 _file_name = _path + 'RA-' +str(i) + '-' + str( int(_ids[i][0]) ) + '-' + str(args.type) + '.png'298299 # the original image300 fix,ax = plt.subplots(1)301 ax.imshow(_test[i], origin='lower')302 plt.title(' Prior conf=' + format(RA_results[i][7][args.type],'.4f'))303 plt.xlabel('ID='+str(int(_ids[i][0])))304 plt.savefig(_path + 'RA-ori-' + str(i) + '-' + str( int(_ids[i][0]) ) + '-' + str(args.type) + '.png')305 plt.close('all')306307 # the attacked image308 fig,ax = plt.subplots(1)309 ax.set_aspect('equal')310 _cdiff = 0.0311 312 # get the attacking pixels 313 ## draw circles of repeated attacks 314 for j in range(args.RA):315 _px, _py = int(RA_results[j * args.RAn + i][9][0]), int(RA_results[j * args.RAn + i][9][1])316 print(j, _px, _py)317 _cdiff += RA_results[j * args.RAn + i][6] 318 plt.scatter(_px, _py, color='', edgecolor='b', marker='o', alpha=.5, s=150)319 _test[i][_py,_px] = RA_results[j * args.RAn + i][9][2], RA_results[j * args.RAn + i][9][3], RA_results[j * args.RAn + i][9][4] 320 321 _title = ' cdiff=' + format(_cdiff/args.RA,'.4f')322 plt.title(_title)323 plt.xlabel('ID='+str(int(_ids[i][0])))324 ax.imshow(_test[i], origin='lower')325 plt.savefig(_file_name)326 plt.close('all')327 328 os._exit(0) 329 330331 attacker = PixelAttacker([model], test, class_names)332333 print('Starting attack')334 335 if args.LP:336 results = attacker.attack_all_least([model], samples=args.samples, pixels=args.pixels, targeted=args.targeted,337 maxiter=args.maxiter, popsize=args.popsize, verbose=args.verbose, DE=args.DE, 338 epsilon=args.epsilon, LS=args.LS, no_stop=args.no_stop)339 else:340 results = attacker.attack_all([model], samples=args.samples, pixels=args.pixels, targeted=args.targeted,341 maxiter=args.maxiter, popsize=args.popsize, verbose=args.verbose, DE=args.DE, 342 epsilon=args.epsilon, LS=args.LS, no_stop=args.no_stop)343344 columns = ['model', 'pixels', 'image', 'true', 'predicted', 'success', 'cdiff', 'prior_probs', 'predicted_probs', 'perturbation']345 results_table = pd.DataFrame(results, columns=columns)346347 print(results_table[['model', 'pixels', 'image', 'true', 'predicted', 'success']])348349 print('Saving to', args.save)350 with open(args.save, 'wb') as file:351 pickle.dump(results, file) ...

Full Screen

Full Screen

statistics.py

Source:statistics.py Github

copy

Full Screen

1import pickle2import matplotlib.pyplot as plt3from mpl_toolkits.mplot3d import Axes3D4from matplotlib import cm5from matplotlib.colors import LightSource6import numpy as np7def read_st(fn, n):8# fn: file name9# n: number of samples10# read the data from the file fn and return the data11 # get the number sample from pickle file12 _f = open(fn.replace('txt','pkl'), 'rb')13 _d = pickle.load(_f)14 sn = len(_d)15 _f.close()16 Data = [] # for all samples17 f = open(fn,"r")18 # skip the two lines:19 # Evaluating model_120 # Starting attack21 line = f.readline()22 line = f.readline()23 line = f.readline().split()24 for i in range(sn):25 data = [] # for one sample26 data.append( float(line[5] ) )27 data.append( float( f.readline().split()[3] ))28 line = f.readline().split()29 while(len(line) == 5):30 data.append( float(line[4]) )31 line = f.readline().split()32 # skip the line 33 # The minimal number of successful attacking pixels is 34 if len(line) != 8: line = f.readline().split()35 Data.append(data)36 # get the time37 line = f.readline()38 while(line.rfind('user') == -1): 39 line = f.readline()40 user = line.split()[1]41 sys = f.readline().split()[1]42 m1, s1 = user.split('m')[0], user.split('m')[1].split('s')[0]43 m2, s2 = sys.split('m')[0], user.split('m')[1].split('s')[0]44 Time = str(int(m1)+int(m2)) + 'm' + format(float(s1)+float(s2),'.2f') + 's'45 #line.split()[1]46 f.close()47 return Data, Time48def draw_1000s(post_fn='-0-1-0.01-500-1000-10-1'):49 # get the Data50 types = ['DE', 'SHA', 'EBL']51 path='./results/dr/'52 #post_fn = '-0-1-0.01-500-1000-10-1'53 DATA = []54 TIME = []55 for i in range(3):56 _data,_time = read_st(path + types[i] + post_fn + '.txt',10)57 DATA.append(_data)58 TIME.append(_time)59 # print the original confidence60 for i in range(len(DATA[0])):61 print('ID=',i, ' Confidence=', DATA[0][i][1]) 62 # draw DE, SHA, EBL63 for i in range(3):64 data = np.array(DATA[i]) 65 fig, ax = plt.subplots() 66 cdiff,wdiff = 0.0, 0.067 for j in range(len(data)):68 plt.plot(data[j][2:], label=str(j)+': '+format(data[j][1],'.4f')) 69 cdiff += (data[j][1]-data[j][len(data[j])-1])70 wdiff += data[j][1]*(data[j][1]-data[j][len(data[j])-1])71 fig.subplots_adjust(right=0.7, bottom=0.2)72 plt.legend(bbox_to_anchor=(1.01,1), loc=2, borderaxespad=0) #loc='lower right',mode='expand')73 plt.xlabel('iterations' + '\ncdiff='+format(cdiff/len(data),'.4f') + ' wdiff=' + format(wdiff/len(data),'.4f'))74 plt.ylabel('confidence')75 plt.title(types[i] + post_fn + '-' + TIME[i])76 plt.savefig(path+types[i]+post_fn+'.png')77 plt.cla()78 plt.clf()79 plt.close('all')80 81 # draw the confidence for each sample with DE, SHA and EBL82 for i in range(len(DATA[0])):83 plt.figure(clear=True)84 X = np.linspace(1,1000,1000,endpoint=True)85 plt.title('ID=' + str(i) +' Confidence='+ format(DATA[0][i][1],'.5f') )86 for j in range(3):87 plt.plot(X, DATA[j][i][2:], label=types[j])88 plt.legend()89 plt.savefig(path + 'id-' + str(i) + post_fn + '.png')90# draw the scater of positive and negative samples91def draw_1000_scater(path='./results/dr/', post_fn='',le=0):92 # get the Data93 types = ['EBL'] 94 DATA = []95 TIME = []96 label = ['negative', 'positive']97 for i in range(2):98 _data,_time = read_st(path + types[0] + post_fn + str(i)+'.txt',1000)99 DATA.append(_data)100 TIME.append(_time)101 102 cdiff,wdiff = 0.0, 0.0103 for j in range(2):104 nsucess = 0 105 fig, ax = plt.subplots()106 data = DATA[j]107 dlen = len(data)108 x, y = np.zeros((2,dlen)), np.zeros((2,dlen))109 for k in range(dlen):110 elen = len(data[k])111 x[j][k] = data[k][1]112 y[j][k] = data[k][elen-1]113 if y[j][k] < 0.5: nsucess +=1 # the number of sucessful attack114 plt.scatter(x[j], y[j], label=label[j], alpha=0.5)115 cbar = plt.colorbar()116 cdiff = np.sum(x[j] - y[j])117 wdiff = np.sum(x[j]*(x[j] - y[j]))118 fig.subplots_adjust(bottom=0.2) 119 plt.xlabel('Confidence before attack' + '\ncdiff='+format(cdiff/len(data),'.4f') + ' wdiff=' + format(wdiff/len(data),'.4f') + ' sucess=' + format(nsucess/len(data), '.4f'))120 plt.ylabel('Confidence after attack')121 stitle = post_fn.split('-')122 stitle[6]= str(dlen)123 st = '-'.join(stitle) 124 plt.title(types[0] + st + str(j) + '-' + TIME[j])125 plt.savefig(path+types[0]+ st + str(j)+'.png')126 plt.cla()127 plt.clf()128 plt.close('all')129def draw_LP(path='./results/dr/', dtype=1, DE='EBL',post_fn='', sn=0):130 #path='./results/dr/'131 f = open(path + DE + post_fn + str(dtype) + '.pkl', 'rb')132 data = pickle.load(f)133 f.close()134 sn = len(data)135 LP_data = np.zeros((3,sn))136 nsucess, npixels = 0, 0137 for i in range(sn):138 LP_data[0,i] = data[i][1] # the number of pixels of the attack139 LP_data[1,i] = data[i][8][dtype] # the confidence after the attack140 LP_data[2,i] = data[i][7][dtype] # the confidence before the attack141 if data[i][8][dtype] < 0.5: 142 nsucess += 1143 npixels += data[i][1]144 145 cdiff, wdiff = np.sum(LP_data[2] - LP_data[1])/sn, np.sum((LP_data[2]-LP_data[1])/LP_data[0])/sn146 # 147 ylabels = ['The least number of pixels', 'The confiderence after attack']148 for i in range(2):149 fig, ax = plt.subplots()150 plt.scatter(LP_data[2], LP_data[i], alpha=0.5)151 plt.colorbar()152 plt.xlabel('Confidence before attack' + '\ncdiff='+format(cdiff,'.4f') + ' wdiff=' + format(wdiff,'.4f') + ' success=' + format(nsucess/len(data), '.4f') )153 plt.ylabel(ylabels[i])154 fig.subplots_adjust(bottom=0.2)155 plt.title(DE + post_fn + str(dtype) + '-LP-' + format(npixels/nsucess,'.2f'))156 plt.savefig(path + DE + post_fn + str(dtype) + '-LP-' + str(i) + '.png')157 plt.cla()158 plt.clf()159 plt.close('all')160 ## draw 3d scatter plots161 #ax = plt.subplot(projection='3d') 162 # for xx, yy, zz in zip(LP_data[2], LP_data[1], LP_data[0]):163 # color = np.random.random(3) # 随机颜色元祖164 # ax.bar3d(165 # xx, # 每个柱的x坐标166 # yy, # 每个柱的y坐标167 # 0, # 每个柱的起始坐标168 # dx=1, # x方向的宽度169 # dy=1, # y方向的厚度170 # dz=zz)#, # z方向的高度171 # #color=color) #每个柱的颜色172 fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) 173 cmap = cm.viridis174 ax.scatter(LP_data[2], LP_data[1], LP_data[0], c='b', cmap=cmap, alpha=0.4, linewidth=0) 175 #fig.colorbar()176 ax.set_zlabel('Number of attacking pixels') # 坐标轴177 ax.set_ylabel('Confidence after attack')178 ax.set_xlabel('Confidence before attack') 179 plt.title('cdiff='+format(cdiff,'.4f') + ' wdiff=' + format(wdiff,'.4f') + ' LP=' + format(npixels/nsucess,'.2f') + ' success=' + format(nsucess/len(data), '.4f'))180 plt.savefig(path + DE + post_fn + str(dtype) + '-LP-3D.png')181 plt.close()182def draw_RA(source='dr',type=0, RAn=10, RA=True):183 for i in range(10): #min(len(_ids), args.RAn)):184 _path = './results/' + source + '/'185 _file_name = _path + 'RA-' +str(i) + '-' + str( int(_ids[i][0]) ) + '-' + str(type) + '.png'186 # the original image187 fix,ax = plt.subplots(1)188 ax.imshow(_test[i], origin='lower')189 plt.title(' Prior conf=' + format(RA_results[i][7][type],'.4f'))190 plt.xlabel('ID='+str(int(_ids[i][0])))191 plt.savefig(_path + 'RA-ori-' + str(i) + '-' + str( int(_ids[i][0]) ) + '-' + str(type) + '.png')192 plt.close('all')193 # the attacked image194 fig,ax = plt.subplots(1)195 ax.set_aspect('equal')196 _cdiff = 0.0197 198 # get the attacking pixels 199 ## draw circles of repeated attacks 200 for j in range(RAn):201 _px, _py = int(RA_results[j * RAn + i][9][0]), int(RA_results[j * RAn + i][9][1])202 _cdiff += RA_results[j * RAn + i][6] 203 plt.scatter(_px, _py, color='', edgecolor='b', marker='o', alpha=.5, s=150)204 _test[i][_py,_px] = RA_results[j * RAn + i][9][2], RA_results[j * RAn + i][9][3], RA_results[j * RAn + i][9][4] 205 _title = ' cdiff=' + format(_cdiff/RAn,'.4f')206 plt.title(_title)207 plt.xlabel('ID='+str(int(_ids[i][0])))208 ax.imshow(_test[i], origin='lower')209 plt.savefig(_file_name)210 plt.close('all') 211if __name__ == '__main__': 212 draw_1000s('-0-1-0.01-1000-1000-10-1')...

Full Screen

Full Screen

diff.py

Source:diff.py Github

copy

Full Screen

...10from ..output.formatting import to_hex_and_str11__all__ = ['cdiff', 'cdiff_objs', 'unified_byte_diff', 'unified_obj_diff']12def cdiff(path1, path2, n: int = 3):13 with open(path1, 'r', encoding='utf-8') as f1, open(path2, 'r', encoding='utf-8') as f2:14 _cdiff(f1.read().splitlines(), f2.read().splitlines(), path1, path2, n=n)15def cdiff_objs(obj1, obj2, fmt: Optional[str] = 'yaml', n: int = 3):16 """17 Print a comparison of the given objects when serialized with the given output format18 :param obj1: A serializable object19 :param obj2: A serializable object20 :param fmt: An output format (one of: json, yaml, str)21 :param n: Number of lines of context to include22 """23 str1, str2 = _objs_to_strs(obj1, obj2, fmt)24 _cdiff(str1.splitlines(), str2.splitlines(), 'obj1', 'obj2', n=n)25def _objs_to_strs(obj1, obj2, fmt: Optional[str] = 'yaml') -> tuple[str, str]:26 if fmt == 'json':27 str1 = json.dumps(obj1, sort_keys=True, indent=4, cls=PermissiveJSONEncoder)28 str2 = json.dumps(obj2, sort_keys=True, indent=4, cls=PermissiveJSONEncoder)29 elif fmt in ('yaml', 'yml'):30 str1, str2 = yaml_dump(obj1), yaml_dump(obj2)31 elif fmt in (None, 'str'):32 str1, str2 = str(obj1), str(obj2)33 else:34 raise ValueError(f'Invalid cdiff format: {fmt!r}')35 return str1, str236def _cdiff(a, b, name_a: str = '', name_b: str = '', n: int = 3):37 for i, line in enumerate(unified_diff(a, b, name_a, name_b, n=n, lineterm='')):38 if line.startswith('+') and i > 1:39 print(colored(line, 2))40 elif line.startswith('-') and i > 1:41 print(colored(line, 1))42 elif line.startswith('@@ '):43 print(colored(line, 6), end='\n\n')44 else:45 print(line)46def unified_obj_diff(47 obj1, obj2, fmt: Optional[str] = 'yaml', n: int = 3, lineterm: str = '', color: bool = True,48):49 str1, str2 = _objs_to_strs(obj1, obj2, fmt)50 a = str1.splitlines()...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful