mnist_defense_nad.py 4.9 KB
Newer Older
Z
zheng-huanhuan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright 2019 Huawei Technologies Co., Ltd
#
# 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.
"""defense example using nad"""
15
import os
Z
zheng-huanhuan 已提交
16
import sys
Z
zheng-huanhuan 已提交
17 18 19 20 21 22

import numpy as np
from mindspore import Tensor
from mindspore import context
from mindspore import nn
from mindspore.nn import SoftmaxCrossEntropyWithLogits
23 24
from mindspore.train import Model
from mindspore.train.callback import LossMonitor
Z
zheng-huanhuan 已提交
25 26 27 28 29

from mindarmour.attacks import FastGradientSignMethod
from mindarmour.defenses import NaturalAdversarialDefense
from mindarmour.utils.logger import LogUtil

30 31
from lenet5_net import LeNet5

Z
zheng-huanhuan 已提交
32 33 34 35 36
sys.path.append("..")
from data_processing import generate_mnist_dataset


LOGGER = LogUtil.get_instance()
37
LOGGER.set_level("INFO")
Z
zheng-huanhuan 已提交
38 39 40 41
TAG = 'Nad_Example'


def test_nad_method():
42
    """
43
    NAD-Defense test.
44
    """
45 46 47 48 49
    mnist_path = "./MNIST_unzip/"
    batch_size = 32
    # 1. train original model
    ds_train = generate_mnist_dataset(os.path.join(mnist_path, "train"),
                                      batch_size=batch_size, repeat_size=1)
50 51 52
    net = LeNet5()
    loss = SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
    opt = nn.Momentum(net.trainable_params(), 0.01, 0.09)
53 54 55
    model = Model(net, loss, opt, metrics=None)
    model.train(10, ds_train, callbacks=[LossMonitor()],
                dataset_sink_mode=False)
56 57

    # 2. get test data
58 59
    ds_test = generate_mnist_dataset(os.path.join(mnist_path, "test"),
                                     batch_size=batch_size, repeat_size=1)
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    inputs = []
    labels = []
    for data in ds_test.create_tuple_iterator():
        inputs.append(data[0].astype(np.float32))
        labels.append(data[1])
    inputs = np.concatenate(inputs)
    labels = np.concatenate(labels)

    # 3. get accuracy of test data on original model
    net.set_train(False)
    acc_list = []
    batchs = inputs.shape[0] // batch_size
    for i in range(batchs):
        batch_inputs = inputs[i*batch_size : (i + 1)*batch_size]
        batch_labels = labels[i*batch_size : (i + 1)*batch_size]
        logits = net(Tensor(batch_inputs)).asnumpy()
        label_pred = np.argmax(logits, axis=1)
        acc_list.append(np.mean(batch_labels == label_pred))

79 80
    LOGGER.info(TAG, 'accuracy of TEST data on original model is : %s',
                np.mean(acc_list))
81 82 83 84

    # 4. get adv of test data
    attack = FastGradientSignMethod(net, eps=0.3, loss_fn=loss)
    adv_data = attack.batch_generate(inputs, labels)
85
    LOGGER.info(TAG, 'adv_data.shape is : %s', adv_data.shape)
86 87 88 89 90 91 92 93 94 95 96

    # 5. get accuracy of adv data on original model
    acc_list = []
    batchs = adv_data.shape[0] // batch_size
    for i in range(batchs):
        batch_inputs = adv_data[i*batch_size : (i + 1)*batch_size]
        batch_labels = labels[i*batch_size : (i + 1)*batch_size]
        logits = net(Tensor(batch_inputs)).asnumpy()
        label_pred = np.argmax(logits, axis=1)
        acc_list.append(np.mean(batch_labels == label_pred))

97 98
    LOGGER.info(TAG, 'accuracy of adv data on original model is : %s',
                np.mean(acc_list))
99 100 101

    # 6. defense
    net.set_train()
102 103
    nad = NaturalAdversarialDefense(net, loss_fn=loss, optimizer=opt,
                                    bounds=(0.0, 1.0), eps=0.3)
104 105 106 107 108 109 110 111 112 113 114 115 116
    nad.batch_defense(inputs, labels, batch_size=32, epochs=10)

    # 7. get accuracy of test data on defensed model
    net.set_train(False)
    acc_list = []
    batchs = inputs.shape[0] // batch_size
    for i in range(batchs):
        batch_inputs = inputs[i*batch_size : (i + 1)*batch_size]
        batch_labels = labels[i*batch_size : (i + 1)*batch_size]
        logits = net(Tensor(batch_inputs)).asnumpy()
        label_pred = np.argmax(logits, axis=1)
        acc_list.append(np.mean(batch_labels == label_pred))

117 118
    LOGGER.info(TAG, 'accuracy of TEST data on defensed model is : %s',
                np.mean(acc_list))
119 120 121 122 123 124 125 126 127 128 129

    # 8. get accuracy of adv data on defensed model
    acc_list = []
    batchs = adv_data.shape[0] // batch_size
    for i in range(batchs):
        batch_inputs = adv_data[i*batch_size : (i + 1)*batch_size]
        batch_labels = labels[i*batch_size : (i + 1)*batch_size]
        logits = net(Tensor(batch_inputs)).asnumpy()
        label_pred = np.argmax(logits, axis=1)
        acc_list.append(np.mean(batch_labels == label_pred))

130 131
    LOGGER.info(TAG, 'accuracy of adv data on defensed model is : %s',
                np.mean(acc_list))
132 133


Z
zheng-huanhuan 已提交
134
if __name__ == '__main__':
135
    # device_target can be "CPU", "GPU" or "Ascend"
136
    context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
137
    test_nad_method()