Exemplo n.º 1
0
    def setUpClass(cls):
        master_seed(seed=1234, set_mxnet=True)
        super().setUpClass()

        cls.x_train_mnist = np.swapaxes(cls.x_train_mnist, 1, 3)
        cls.x_test_mnist = np.swapaxes(cls.x_test_mnist, 1, 3)

        # Create a simple CNN - this one comes from the Gluon tutorial
        net = nn.Sequential()
        with net.name_scope():
            net.add(
                nn.Conv2D(channels=6, kernel_size=5, activation="relu"),
                nn.MaxPool2D(pool_size=2, strides=2),
                nn.Conv2D(channels=16, kernel_size=3, activation="relu"),
                nn.MaxPool2D(pool_size=2, strides=2),
                nn.Flatten(),
                nn.Dense(120, activation="relu"),
                nn.Dense(84, activation="relu"),
                nn.Dense(10),
            )
        net.initialize(init=init.Xavier())

        # Create optimizer
        loss = gluon.loss.SoftmaxCrossEntropyLoss()
        trainer = gluon.Trainer(net.collect_params(), "sgd", {"learning_rate": 0.1})

        # Fit classifier
        classifier = MXClassifier(
            model=net, loss=loss, clip_values=(0, 1), input_shape=(1, 28, 28), nb_classes=10, optimizer=trainer
        )
        classifier.fit(cls.x_train_mnist, cls.y_train_mnist, batch_size=128, nb_epochs=2)
        cls.classifier = classifier

        cls.x_train_mnist = np.swapaxes(cls.x_train_mnist, 1, 3)
        cls.x_test_mnist = np.swapaxes(cls.x_test_mnist, 1, 3)
Exemplo n.º 2
0
    def setUpClass(cls):
        # Get MNIST
        (x_train, y_train), (x_test, y_test), _, _ = load_mnist()
        x_train, y_train = x_train[:NB_TRAIN], y_train[:NB_TRAIN]
        x_test, y_test = x_test[:NB_TEST], y_test[:NB_TEST]
        x_train = np.swapaxes(x_train, 1, 3)
        x_test = np.swapaxes(x_test, 1, 3)
        cls.mnist = (x_train, y_train), (x_test, y_test)

        # Create a simple CNN - this one comes from the Gluon tutorial
        net = nn.Sequential()
        with net.name_scope():
            net.add(nn.Conv2D(channels=6, kernel_size=5, activation='relu'),
                    nn.MaxPool2D(pool_size=2, strides=2),
                    nn.Conv2D(channels=16, kernel_size=3, activation='relu'),
                    nn.MaxPool2D(pool_size=2, strides=2), nn.Flatten(),
                    nn.Dense(120, activation="relu"),
                    nn.Dense(84, activation="relu"), nn.Dense(10))
        net.initialize(init=init.Xavier())

        # Create optimizer
        loss = gluon.loss.SoftmaxCrossEntropyLoss()
        trainer = gluon.Trainer(net.collect_params(), 'sgd',
                                {'learning_rate': 0.1})

        # Fit classifier
        classifier = MXClassifier(model=net,
                                  loss=loss,
                                  clip_values=(0, 1),
                                  input_shape=(1, 28, 28),
                                  nb_classes=10,
                                  optimizer=trainer)
        classifier.fit(x_train, y_train, batch_size=128, nb_epochs=2)
        cls.classifier = classifier
    def test_fit_predict(self):
        (x_train, y_train), (x_test, y_test) = self._mnist

        # Fit classifier
        classifier = MXClassifier((0, 1), self._model, (1, 28, 28), 10,
                                  self._trainer)
        classifier.fit(x_train, y_train, batch_size=128, nb_epochs=2)

        preds = classifier.predict(x_test)
        acc = np.sum(np.argmax(preds, axis=1) == np.argmax(
            y_test, axis=1)) / len(y_test)
        print("\nAccuracy: %.2f%%" % (acc * 100))
        self.assertGreater(acc, 0.1)
Exemplo n.º 4
0
# Step 3: 创建ART分类器

classifier = MXClassifier(model=model,
                          clip_values=(min_pixel_value, max_pixel_value),
                          loss=loss,
                          input_shape=(28, 28, 1),
                          nb_classes=10,
                          optimizer=trainer,
                          ctx=None,
                          channel_index=1,
                          defences=None,
                          preprocessing=(0, 1))

# Step 4: 训练ART分类器

classifier.fit(x_train, y_train, batch_size=64, nb_epochs=3)

# Step 5: 在良性的测试实例上评价ART分类器

predictions = classifier.predict(x_test)
accuracy = np.sum(
    np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)
print('Accuracy on benign test examples: {}%'.format(accuracy * 100))

# Step 6: 生成对抗性测试示例
attack = FastGradientMethod(classifier=classifier, eps=0.2)
x_test_adv = attack.generate(x=x_test)

# Step 7: 通过对抗性测试实例对ART分类器进行评价

predictions = classifier.predict(x_test_adv)