def main(): # PaddlePaddle init paddle.init(use_gpu=True, trainer_count=1) image = paddle.layer.data(name="image", type=paddle.data_type.dense_vector(datadim)) # Add neural network config # option 1. resnet net = resnet_cifar10(image, depth=32) # option 2. vgg # net = vgg_bn_drop(image) out = paddle.layer.fc(input=net, size=classdim, act=paddle.activation.Softmax()) lbl = paddle.layer.data(name="label", type=paddle.data_type.integer_value(classdim)) cost = paddle.layer.classification_cost(input=out, label=lbl) # load parameters with open("params_pass_167.tar", 'r') as f: parameters = paddle.parameters.Parameters.from_tar(f) for sample in create_dataset.test_reader()(): data = sample[0] label = sample[1] probs = paddle.infer(output_layer=out, parameters=parameters, input=[(data, )]) prob = probs[0].tolist() infer_label = prob.index(max(prob)) print(str(label) + " " + str(infer_label))
def inference_network(): # The image is 32 * 32 with RGB representation. data_shape = [3, 32, 32] images = fluid.layers.data(name='pixel', shape=data_shape, dtype='float32') predict = resnet_cifar10(images, 32) # predict = vgg_bn_drop(images) # un-comment to use vgg net return predict
def inference_network(): # 图像是32 * 32的RGB表示. data_shape = [3, 32, 32] images = fluid.layers.data(name='pixel', shape=data_shape, dtype='float32') predict = resnet_cifar10(images, 32) # predict = vgg_bn_drop(images) # 取消注释使用 vgg net return predict
def inference_network(): # The image is 32 * 32 with RGB representation. data_shape = [3, 32, 32] images = fluid.layers.data(name='pixel', shape=data_shape, dtype='float32') #可选的resnet深度20, 32, 44, 56, 110, 1202 ''' 实验数据 深度为32 Test with Pass 9, Loss 0.86, Acc 0.76 深度为110 Test with Pass 9, Loss 0.76, Acc 0.76 ''' predict = resnet_cifar10(images, 32) return predict
def main(): """ Advbox demo which demonstrate how to use advbox. """ TOTAL_NUM = 500 IMG_NAME = 'img' LABEL_NAME = 'label' img = fluid.layers.data(name=IMG_NAME, shape=[3, 32, 32], dtype='float32') # gradient should flow img.stop_gradient = False label = fluid.layers.data(name=LABEL_NAME, shape=[1], dtype='int64') #logits = mnist_cnn_model(img) #logits = vgg_bn_drop(img) logits = resnet_cifar10(img, 32) cost = fluid.layers.cross_entropy(input=logits, label=label) avg_cost = fluid.layers.mean(x=cost) # use CPU #place = fluid.CPUPlace() # use GPU place = fluid.CUDAPlace(0) exe = fluid.Executor(place) BATCH_SIZE = 1 test_reader = paddle.batch(paddle.dataset.cifar.test10(), batch_size=BATCH_SIZE) fluid.io.load_params(exe, "cifar10/", main_program=fluid.default_main_program()) # advbox demo m = PaddleModel(fluid.default_main_program(), IMG_NAME, LABEL_NAME, logits.name, avg_cost.name, (-1, 1), channel_axis=1) attack = FGSM(m) # attack = FGSMT(m) attack_config = {"epsilons": 0.3} # use test data to generate adversarial examples total_count = 0 fooling_count = 0 for data in test_reader(): total_count += 1 adversary = Adversary(data[0][0], data[0][1]) # FGSM non-targeted attack adversary = attack(adversary, **attack_config) # FGSMT targeted attack # tlabel = 0 # adversary.set_target(is_targeted_attack=True, target_label=tlabel) # adversary = attack(adversary, **attack_config) if adversary.is_successful(): fooling_count += 1 print( 'attack success, original_label=%d, adversarial_label=%d, count=%d' % (data[0][1], adversary.adversarial_label, total_count)) # plt.imshow(adversary.target, cmap='Greys_r') # plt.show() # np.save('adv_img', adversary.target) else: print('attack failed, original_label=%d, count=%d' % (data[0][1], total_count)) if total_count >= TOTAL_NUM: print( "[TEST_DATASET]: fooling_count=%d, total_count=%d, fooling_rate=%f" % (fooling_count, total_count, float(fooling_count) / total_count)) break print("fgsm attack done")
def main(): # datadim = 3 * 32 * 32 datadim = 200 * 200 classdim = 2 # PaddlePaddle init paddle.init(use_gpu=True, trainer_count=4) image = paddle.layer.data(name="image", type=paddle.data_type.dense_vector(datadim)) # Add neural network config # option 1. resnet net = resnet_cifar10(image, depth=32) # option 2. vgg # net = vgg_bn_drop(image) out = paddle.layer.fc(input=net, size=classdim, act=paddle.activation.Softmax()) lbl = paddle.layer.data(name="label", type=paddle.data_type.integer_value(classdim)) cost = paddle.layer.classification_cost(input=out, label=lbl) # Create parameters parameters = paddle.parameters.create(cost) # Create optimizer momentum_optimizer = paddle.optimizer.Momentum( momentum=0.9, regularization=paddle.optimizer.L2Regularization(rate=0.0002 * BATCH_SIZE), learning_rate=0.1 / BATCH_SIZE, learning_rate_decay_a=0.1, learning_rate_decay_b=25655 * 20, learning_rate_schedule='discexp') # Create trainer trainer = paddle.trainer.SGD(cost=cost, parameters=parameters, update_equation=momentum_optimizer) # End batch and end pass event handler def event_handler(event): if isinstance(event, paddle.event.EndIteration): if event.batch_id % 10 == 0: print "\nPass %d, Batch %d, Cost %f, %s" % ( event.pass_id, event.batch_id, event.cost, event.metrics) else: sys.stdout.write('.') sys.stdout.flush() if isinstance(event, paddle.event.EndPass): # save parameters with open('params_pass_%d.tar' % event.pass_id, 'w') as f: trainer.save_parameter_to_tar(f) result = trainer.test(reader=paddle.batch( create_dataset.test_reader(), batch_size=BATCH_SIZE), feeding={ 'image': 0, 'label': 1 }) print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics) # Save the inference topology to protobuf. # inference_topology = paddle.topology.Topology(layers=out) # with open("inference_topology.pkl", 'wb') as f: # inference_topology.serialize_for_inference(f) trainer.train(reader=paddle.batch(paddle.reader.shuffle( create_dataset.train_reader(), buf_size=10000), batch_size=BATCH_SIZE), num_passes=200, event_handler=event_handler, feeding={ 'image': 0, 'label': 1 }) # inference from PIL import Image import numpy as np import os def load_image(file): im = Image.open(file) im = im.resize((32, 32), Image.ANTIALIAS) im = np.array(im).astype(np.float32) # The storage order of the loaded image is W(widht), # H(height), C(channel). PaddlePaddle requires # the CHW order, so transpose them. im = im.transpose((2, 0, 1)) # CHW # In the training phase, the channel order of CIFAR # image is B(Blue), G(green), R(Red). But PIL open # image in RGB mode. It must swap the channel order. im = im[(2, 1, 0), :, :] # BGR im = im.flatten() im = im / 255.0 return im test_data = [] cur_dir = os.path.dirname(os.path.realpath(__file__)) test_data.append((load_image(cur_dir + '/image/dog.png'), )) # users can remove the comments and change the model name # with open('params_pass_50.tar', 'r') as f: # parameters = paddle.parameters.Parameters.from_tar(f) probs = paddle.infer(output_layer=out, parameters=parameters, input=test_data) lab = np.argsort(-probs) # probs and lab are the results of one batch data print "Label of image/dog.png is: %d" % lab[0][0]