mnist_tutorial_fgsm.py 2.8 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
G
gx_wind 已提交
14 15 16 17 18 19 20 21 22 23 24
"""
FGSM demos on mnist using advbox tool.
"""
import paddle.v2 as paddle
import paddle.v2.fluid as fluid
import matplotlib.pyplot as plt
import numpy as np

from advbox.models.paddle import PaddleModel
from advbox.attacks.gradientsign import GradientSignAttack

G
gx_wind 已提交
25

G
gx_wind 已提交
26 27 28 29 30 31 32 33 34 35
def cnn_model(img):
    """
    Mnist cnn model
    Args:
        img(Varaible): the input image to be recognized
    Returns:
        Variable: the label prediction
    """
    #conv1 = fluid.nets.conv2d()
    conv_pool_1 = fluid.nets.simple_img_conv_pool(
G
gx_wind 已提交
36 37 38 39 40 41
        input=img,
        num_filters=20,
        filter_size=5,
        pool_size=2,
        pool_stride=2,
        act='relu')
G
gx_wind 已提交
42 43

    conv_pool_2 = fluid.nets.simple_img_conv_pool(
G
gx_wind 已提交
44 45 46 47 48 49
        input=conv_pool_1,
        num_filters=50,
        filter_size=5,
        pool_size=2,
        pool_stride=2,
        act='relu')
G
gx_wind 已提交
50

G
gx_wind 已提交
51
    logits = fluid.layers.fc(input=conv_pool_2, size=10, act='softmax')
G
gx_wind 已提交
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
    return logits


def main():
    """
    Advbox demo which demonstrate how to use advbox.
    """
    IMG_NAME = 'img'
    LABEL_NAME = 'label'

    img = fluid.layers.data(name=IMG_NAME, shape=[1, 28, 28], dtype='float32')
    # gradient should flow
    img.stop_gradient = False
    label = fluid.layers.data(name=LABEL_NAME, shape=[1], dtype='int64')
    logits = cnn_model(img)
    cost = fluid.layers.cross_entropy(input=logits, label=label)
    avg_cost = fluid.layers.mean(x=cost)

    place = fluid.CPUPlace()
    exe = fluid.Executor(place)

    BATCH_SIZE = 1
    train_reader = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.mnist.train(), buf_size=500),
        batch_size=BATCH_SIZE)
    feeder = fluid.DataFeeder(
G
gx_wind 已提交
79 80 81
        feed_list=[IMG_NAME, LABEL_NAME],
        place=place,
        program=fluid.default_main_program())
G
gx_wind 已提交
82

G
gx_wind 已提交
83 84
    fluid.io.load_params(
        exe, "./mnist/", main_program=fluid.default_main_program())
G
gx_wind 已提交
85 86

    # advbox demo
G
gx_wind 已提交
87 88
    m = PaddleModel(fluid.default_main_program(), IMG_NAME, LABEL_NAME,
                    logits.name, avg_cost.name, (-1, 1))
G
gx_wind 已提交
89 90 91 92 93 94 95 96
    att = GradientSignAttack(m)
    for data in train_reader():
        # fgsm attack
        adv_img = att(data)
        plt.imshow(n[0][0], cmap='Greys_r')
        plt.show()
        #np.save('adv_img', adv_img)
        break
G
gx_wind 已提交
97 98


G
gx_wind 已提交
99 100
if __name__ == '__main__':
    main()