Esempio n. 1
0
def main(argv=None):
    datasets = FLAGS.datasets
    start=FLAGS.start
    end=FLAGS.end
    if 'mnist' == datasets:
        train_start = 0
        train_end = 60000
        test_start = 0
        test_end = 10000

        # Get MNIST test data
        X_train, Y_train, X_test, Y_test = data_mnist(train_start=train_start,
                                                      train_end=train_end,
                                                      test_start=test_start,
                                                      test_end=test_end)
        sample = X_test[start:end]
        #imsave(FLAGS.sample, deprocess_image_1(sample))
    elif 'cifar10' == datasets:
        preprocess_image = preprocess_image_1
        train_start = 0
        train_end = 50000
        test_start = 0
        test_end = 10000

        # Get CIFAR10 test data
        X_train, Y_train, X_test, Y_test = data_cifar10(train_start=train_start,
                                                                           train_end=train_end,
                                                                           test_start=test_start,
                                                                           test_end=test_end,
                                                                           preprocess=preprocess_image)
        sample = X_train[0:10000]
        #imsave(FLAGS.sample, deprocess_image_1(sample))
    elif 'svhn' == datasets:
        # choose the method of preprocess image
        preprocess_image = preprocess_image_1

        train_start = 0
        train_end = 73257
        test_start = 0
        test_end = 26032

        # Get SVHN test data
        X_train, Y_train, X_test, Y_test = data_svhn(train_start=train_start,
                                                     train_end=train_end,
                                                     test_start=test_start,
                                                     test_end=test_end,
                                                     preprocess=preprocess_image)
        sample = X_test[0:100]
        imsave(FLAGS.sample, deprocess_image_1(sample))

    store_path = 'test'
    suc,total=cw(datasets=datasets,
                  sample=sample,
                  model_name=FLAGS.model,
                  target=FLAGS.target,
                  store_path=store_path,
	                ini_con=0.1,start=start,end=end)
    print(suc)
    print(total)
Esempio n. 2
0
def main(argv=None):
    datasets = FLAGS.datasets
    if 'mnist' == datasets:
        train_start = 0
        train_end = 60000
        test_start = 0
        test_end = 10000

        # Get MNIST test data
        X_train, Y_train, X_test, Y_test = data_mnist(train_start=train_start,
                                                      train_end=train_end,
                                                      test_start=test_start,
                                                      test_end=test_end)
        sample = X_test[0:1000]

    elif 'cifar10' == datasets:
        preprocess_image = preprocess_image_1
        train_start = 0
        train_end = 50000
        test_start = 0
        test_end = 10000

        # Get CIFAR10 test data
        X_train, Y_train, fn_train, X_test, Y_test, fn_test = data_cifar10(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)
        sample = X_test[198:199]
        imsave(FLAGS.sample, deprocess_image_1(sample))
    elif 'svhn' == datasets:
        # choose the method of preprocess image
        preprocess_image = preprocess_image_1

        train_start = 0
        train_end = 73257
        test_start = 0
        test_end = 26032

        # Get SVHN test data
        X_train, Y_train, X_test, Y_test = data_svhn(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)
        sample = X_test[198:199]
        imsave(FLAGS.sample, deprocess_image_1(sample))

    store_path = '../datasets/experiment/mnist/fgsm/test'

    fgsm(datasets=datasets,
         sample=sample,
         model_name=FLAGS.model_name,
         store_path=store_path,
         step_size=FLAGS.step_size,
         epoch=FLAGS.epoch)
Esempio n. 3
0
def main(argv=None):
    datasets = FLAGS.datasets
    if 'mnist' == datasets:
        train_start = 0
        train_end = 60000
        test_start = 0
        test_end = 10000

        # Get MNIST test data
        X_train, Y_train, X_test, Y_test = data_mnist(train_start=train_start,
                                                      train_end=train_end,
                                                      test_start=test_start,
                                                      test_end=test_end)
        sample = X_test[0:10]

    elif 'cifar10' == datasets:
        preprocess_image = preprocess_image_1
        train_start = 0
        train_end = 50000
        test_start = 0
        test_end = 10000

        # Get CIFAR10 test data
        X_train, Y_train, X_test, Y_test = data_cifar10(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)
        sample = X_test[0:2]
        #imsave('a.png', deprocess_image_3(sample))
    elif 'svhn' == datasets:
        # choose the method of preprocess image
        preprocess_image = preprocess_image_1

        train_start = 0
        train_end = 73257
        test_start = 0
        test_end = 26032

        # Get SVHN test data
        X_train, Y_train, X_test, Y_test = data_svhn(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)
        sample = X_test[198:199]
        imsave(FLAGS.sample, deprocess_image_1(sample))

    store_path = 'test0.03'

    bim(datasets=datasets,
        sample=sample,
        model_name=FLAGS.model,
        store_path=store_path,
        step_size='0.03')
Esempio n. 4
0
def main(argv=None):
    datasets = FLAGS.datasets
    if 'mnist' == datasets:
        train_start = 0
        train_end = 60000
        test_start = 0
        test_end = 10000

        # Get MNIST test data
        X_train, Y_train, X_test, Y_test = data_mnist(train_start=train_start,
                                                      train_end=train_end,
                                                      test_start=test_start,
                                                      test_end=test_end)
        sample = X_test[0:1]
        imsave(FLAGS.sample, deprocess_image_1(sample))
    elif 'cifar10' == datasets:
        preprocess_image = preprocess_image_1
        train_start = 0
        train_end = 50000
        test_start = 0
        test_end = 10000

        # Get CIFAR10 test data
        X_train, Y_train, X_test, Y_test = data_cifar10(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)
        sample = X_test[198:199]
        imsave(FLAGS.sample, deprocess_image_1(sample))
    elif 'svhn' == datasets:
        # choose the method of preprocess image
        preprocess_image = preprocess_image_1

        train_start = 0
        train_end = 73257
        test_start = 0
        test_end = 26032

        # Get SVHN test data
        X_train, Y_train, X_test, Y_test = data_svhn(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)
        sample = X_test[198:199]
        imsave(FLAGS.sample, deprocess_image_1(sample))
    jsma(datasets=FLAGS.datasets,
         sample_path=FLAGS.sample,
         model_name=FLAGS.model,
         target=FLAGS.target,
         store_path=FLAGS.store_path)
Esempio n. 5
0
def get_data(datasets):
    if 'mnist' == datasets:
        train_start = 0
        train_end = 60000
        test_start = 0
        test_end = 10000

        # Get MNIST test data
        X_train, Y_train, X_test, Y_test = data_mnist(train_start=train_start,
                                                      train_end=train_end,
                                                      test_start=test_start,
                                                      test_end=test_end)
    elif 'cifar10' == datasets:
        # choose the method of preprocess image
        preprocess_image = preprocess_image_1

        train_start = 0
        train_end = 50000
        test_start = 0
        test_end = 10000

        # Get CIFAR10 test data
        X_train, Y_train, X_test, Y_test = data_cifar10(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)

    elif 'svhn' == datasets:
        # choose the method of preprocess image
        preprocess_image = preprocess_image_1

        train_start = 0
        train_end = 73257
        test_start = 0
        test_end = 26032

        # Get SVHN test data
        X_train, Y_train, X_test, Y_test = data_svhn(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)
    return X_train, Y_train, X_test, Y_test
Esempio n. 6
0
def mutation_tutorial(datasets,
                      attack,
                      sample_path,
                      store_path,
                      model_path,
                      level=1,
                      test_num=100,
                      mutation_number=1000,
                      mutated=False):
    if 'mnist' == datasets:
        train_start = 0
        train_end = 60000
        test_start = 0
        test_end = 10000

        # Get MNIST test data
        X_train, Y_train, X_test, Y_test = data_mnist(train_start=train_start,
                                                      train_end=train_end,
                                                      test_start=test_start,
                                                      test_end=test_end)
    elif 'cifar10' == datasets:
        preprocess_image = preprocess_image_1
        train_start = 0
        train_end = 50000
        test_start = 0
        test_end = 10000

        # Get CIFAR10 test data
        X_train, Y_train, fn_train, X_test, Y_test, fn_test = data_cifar10(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)
    elif 'svhn' == datasets:
        # choose the method of preprocess image
        preprocess_image = preprocess_image_1

        train_start = 0
        train_end = 73257
        test_start = 0
        test_end = 26032

        # Get SVHN test data
        X_train, Y_train, X_test, Y_test = data_svhn(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)

    sess, preds, x, y, model, feed_dict = model_load(datasets,
                                                     model_path + datasets)

    # Generate random matution matrix for mutations
    store_path = store_path + attack + '/' + datasets + '/' + str(level)
    if not os.path.exists(store_path):
        os.makedirs(store_path)
    result = ''

    sample_path = sample_path + attack + '/' + datasets
    [image_list, image_files, real_labels,
     predicted_labels] = utils.get_data_mutation_test(sample_path)
    index = np.random.choice(len(image_files), test_num, replace=False)
    image_list = np.asarray(image_list)[index]
    image_files = np.asarray(image_files)[index].tolist()
    predicted_labels = np.asarray(predicted_labels)[index].tolist()

    seed_number = len(image_list)
    if datasets == 'mnist':
        img_rows = 28
        img_cols = 28
        mutation_test = MutationTest(img_rows, img_cols, seed_number,
                                     mutation_number, level)
        mutation_test.mutation_generate(mutated, store_path,
                                        utils.generate_value_1)
    elif datasets == 'cifar10' or datasets == 'svhn':
        img_rows = 32
        img_cols = 32
        mutation_test = MutationTest(img_rows, img_cols, seed_number,
                                     mutation_number, level)
        mutation_test.mutation_generate(mutated, store_path,
                                        utils.generate_value_3)

    store_string, result = mutation_test.mutation_test_adv(
        preprocess_image_1, result, image_list, predicted_labels, sess, x,
        preds, image_files, feed_dict)

    with open(store_path + "/adv_result.csv", "w") as f:
        f.write(store_string)

    path = store_path + '/ori_jsma'
    if not os.path.exists(path):
        os.makedirs(path)

    preds_test = np.asarray([])
    for i in range(40):
        preds_test = np.concatenate(
            (preds_test,
             model_argmax(sess,
                          x,
                          preds,
                          X_test[i * 250:(i + 1) * 250],
                          feed=feed_dict)))
    inds_correct = np.asarray(np.where(preds_test == Y_test.argmax(axis=1))[0])
    inds_correct = inds_correct[np.random.choice(len(inds_correct),
                                                 test_num,
                                                 replace=False)]
    image_list = X_test[inds_correct]
    real_labels = Y_test[inds_correct].argmax(axis=1)

    np.save(path + '/ori_x.npy', np.asarray(image_list))
    np.save(path + '/ori_y.npy', np.asarray(real_labels))

    image_list = np.load(path + '/ori_x.npy')
    real_labels = np.load(path + '/ori_y.npy')

    store_string, result = mutation_test.mutation_test_ori(
        result, image_list, sess, x, preds, feed_dict)

    with open(store_path + "/ori_result.csv", "w") as f:
        f.write(store_string)

    with open(store_path + "/result.csv", "w") as f:
        f.write(result)

    # Close TF session
    sess.close()
    print('Finish.')
Esempio n. 7
0
def detect_adv_samples(datasets, model_path, sample_path, store_path,
                       attack_type):
    print('Loading the data and model...')
    # Load the model
    sess, preds, x, y, model, feed_dict = model_load(datasets, model_path)

    # # Load the dataset
    if 'mnist' == datasets:
        train_start = 0
        train_end = 60000
        test_start = 0
        test_end = 10000

        # Get MNIST test data
        X_train, Y_train, X_test, Y_test = data_mnist(train_start=train_start,
                                                      train_end=train_end,
                                                      test_start=test_start,
                                                      test_end=test_end)
    elif 'cifar10' == datasets:
        preprocess_image = preprocess_image_1
        train_start = 0
        train_end = 50000
        test_start = 0
        test_end = 10000

        # Get CIFAR10 test data
        X_train, Y_train, fn_train, X_test, Y_test, fn_test = data_cifar10(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)

    # # Refine the normal, noisy and adversarial sets to only include samples for
    # # which the original version was correctly classified by the model
    # preds_test = model_argmax(sess, x, preds, X_test, feed=feed_dict)
    # inds_correct = np.where(preds_test == Y_test.argmax(axis=1))[0]
    # X_test = X_test[inds_correct]
    # X_test = X_test[np.random.choice(len(X_test), 500)]#500
    #
    # # Check attack type, select adversarial and noisy samples accordingly
    # print('Loading adversarial samples...')
    # # Load adversarial samplesx
    # [X_test_adv, adv_image_files, real_labels, predicted_labels] = utils.get_data_mutation_test(sample_path)
    # X_test_adv = preprocess_image_1(np.asarray(X_test_adv).astype('float32'))
    # if len(X_test_adv.shape) < 4:
    #     X_test_adv = np.expand_dims(X_test_adv, axis=3)

    [X_test_adv_train, adv_image_files, real_labels, predicted_labels
     ] = utils.get_data_mutation_test("../datasets/experiment/" + datasets +
                                      "/" + attack_type + "/train")
    [X_test_adv_test, adv_image_files, real_labels, predicted_labels
     ] = utils.get_data_mutation_test("../datasets/experiment/" + datasets +
                                      "/" + attack_type + "/test")
    train_num = len(X_test_adv_train)
    test_num = len(X_test_adv_test)
    X_test_adv = preprocess_image_1(
        np.concatenate((np.asarray(X_test_adv_train),
                        np.asarray(X_test_adv_test))).astype('float32'))
    if len(X_test_adv.shape) < 4:
        X_test_adv = np.expand_dims(X_test_adv, axis=3)

    [X_test_train, adv_image_files, real_labels,
     predicted_labels] = utils.get_data_normal_test("../datasets/experiment/" +
                                                    datasets + "/normal/train")
    [X_test_test, adv_image_files, real_labels,
     predicted_labels] = utils.get_data_normal_test("../datasets/experiment/" +
                                                    datasets + "/normal/test")
    X_test_train = np.asarray(X_test_train)[np.random.choice(len(X_test_train),
                                                             train_num,
                                                             replace=False)]
    X_test_test = np.asarray(X_test_test)[np.random.choice(len(X_test_test),
                                                           test_num,
                                                           replace=False)]
    X_test = preprocess_image_1(
        np.concatenate((np.asarray(X_test_train),
                        np.asarray(X_test_test))).astype('float32'))
    if len(X_test.shape) < 4:
        X_test = np.expand_dims(X_test, axis=3)

    ## Get Bayesian uncertainty scores
    print('Getting Monte Carlo dropout variance predictions...')
    uncerts_normal = get_mc_predictions(sess, x, preds,
                                        X_test).var(axis=0).mean(axis=1)
    uncerts_adv = get_mc_predictions(sess, x, preds,
                                     X_test_adv).var(axis=0).mean(axis=1)

    ## Get KDE scores
    # Get deep feature representations
    print('Getting deep feature representations...')
    X_train_features = get_deep_representations(sess, x, X_train, model,
                                                feed_dict)
    X_test_normal_features = get_deep_representations(sess, x, X_test, model,
                                                      feed_dict)
    X_test_adv_features = get_deep_representations(sess, x, X_test_adv, model,
                                                   feed_dict)

    # Train one KDE per class
    print('Training KDEs...')
    class_inds = {}
    for i in range(Y_train.shape[1]):
        class_inds[i] = np.where(Y_train.argmax(axis=1) == i)[0]
    kdes = {}
    warnings.warn(
        "Using pre-set kernel bandwidths that were determined "
        "optimal for the specific CNN models of the paper. If you've "
        "changed your model, you'll need to re-optimize the "
        "bandwidth.")
    for i in range(Y_train.shape[1]):
        kdes[i] = KernelDensity(kernel='gaussian',
                                bandwidth=BANDWIDTHS[datasets]) \
            .fit(X_train_features[class_inds[i]])

    # Get model predictions
    print('Computing model predictions...')
    preds_test_normal = model_argmax(sess, x, preds, X_test, feed=feed_dict)
    preds_test_adv = model_argmax(sess, x, preds, X_test_adv, feed=feed_dict)

    # Get density estimates
    print('computing densities...')
    densities_normal = score_samples(kdes, X_test_normal_features,
                                     preds_test_normal)
    densities_adv = score_samples(kdes, X_test_adv_features, preds_test_adv)

    uncerts_pos = uncerts_adv[:]
    uncerts_neg = uncerts_normal[:]
    characteristics, labels = merge_and_generate_labels(
        uncerts_pos, uncerts_neg)
    file_name = os.path.join('../detection/bu/',
                             "%s_%s.npy" % (datasets, attack_type))
    data = np.concatenate((characteristics, labels), axis=1)
    np.save(file_name, data)

    densities_pos = densities_adv[:]
    densities_neg = densities_normal[:]
    characteristics, labels = merge_and_generate_labels(
        densities_pos, densities_neg)
    file_name = os.path.join(
        '../detection/de/',
        "%s_%s_%.4f.npy" % (datasets, attack_type, BANDWIDTHS[datasets]))
    data = np.concatenate((characteristics, labels), axis=1)
    np.save(file_name, data)

    ## Z-score the uncertainty and density values
    uncerts_normal_z, uncerts_adv_z = normalize(uncerts_normal, uncerts_adv)
    densities_normal_z, densities_adv_z = normalize(densities_normal,
                                                    densities_adv)

    ## Build detector
    values, labels = features(densities_pos=densities_adv_z,
                              densities_neg=densities_normal_z,
                              uncerts_pos=uncerts_adv_z,
                              uncerts_neg=uncerts_normal_z)
    X_tr, Y_tr, X_te, Y_te = block_split(values, labels, train_num)

    lr = train_lr(X_tr, Y_tr)

    ## Evaluate detector
    # Compute logistic regression model predictions
    probs = lr.predict_proba(X_te)[:, 1]
    preds = lr.predict(X_te)
    # Compute AUC
    n_samples = int(len(X_te) / 2)
    # The first 2/3 of 'probs' is the negative class (normal and noisy samples),
    # and the last 1/3 is the positive class (adversarial samples).
    _, _, auc_score = compute_roc(probs_neg=probs[:n_samples],
                                  probs_pos=probs[n_samples:])

    precision = precision_score(Y_te, preds)
    recall = recall_score(Y_te, preds)

    y_label_pred = lr.predict(X_te)
    acc = accuracy_score(Y_te, y_label_pred)

    print(
        'Detector ROC-AUC score: %0.4f, accuracy: %.4f, precision: %.4f, recall: %.4f'
        % (auc_score, acc, precision, recall))
Esempio n. 8
0
def batch_attack(datasets, attack, model_path, store_path, nb_classes):
    if 'mnist' == datasets:
        train_start = 0
        train_end = 60000
        test_start = 0
        test_end = 10000

        # Get MNIST test data
        X_train, Y_train, X_test, Y_test = data_mnist(train_start=train_start,
                                                      train_end=train_end,
                                                      test_start=test_start,
                                                      test_end=test_end)
    elif 'cifar10' == datasets:
        preprocess_image = preprocess_image_1
        train_start = 0
        train_end = 50000
        test_start = 0
        test_end = 10000

        # Get CIFAR10 test data
        X_train, Y_train, fn_train, X_test, Y_test, fn_test = data_cifar10(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)
    elif 'svhn' == datasets:
        # choose the method of preprocess image
        preprocess_image = preprocess_image_1

        train_start = 0
        train_end = 73257
        test_start = 0
        test_end = 26032

        # Get SVHN test data
        X_train, Y_train, X_test, Y_test = data_svhn(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)

    store_path = store_path + attack + '/' + datasets
    sample_path = '../datasets/integration/batch_attack/' + datasets + '/'
    sess, preds, x, y, model, feed_dict = model_load(datasets, model_path)
    if os.listdir(sample_path) == []:
        for i in range(len(X_test)):
            sample = X_test[i:i + 1]
            path = sample_path + str(i) + '.png'
            imsave(path, deprocess_image_1(sample))
            current_img = ndimage.imread(path)
            img = np.expand_dims(
                preprocess_image_1(current_img.astype('float64')), 0)
            p = model_argmax(sess, x, preds, img, feed=feed_dict)
            if p != Y_test[i].argmax(axis=0):
                os.remove(path)
        # for i in range(len(X_test)):
        #     sample = X_test[i:i+1]
        #     if model_argmax(sess, x, preds, sample, feed=feed_dict) == Y_test[i].argmax(axis=0):
        #         path = sample_path + str(i) + '.png'
        #         imsave(path, deprocess_image_1(sample))

    sess.close()
    samples = os.listdir(sample_path)
    for sample in samples:
        tf.reset_default_graph()
        if 'blackbox' == attack:
            blackbox(datasets=datasets,
                     sample_path=sample_path + sample,
                     model_path=model_path,
                     store_path=store_path,
                     nb_classes=nb_classes)
        elif 'fgsm' == attack:
            fgsm(datasets=datasets,
                 sample_path=sample_path + sample,
                 model_path=model_path,
                 store_path=store_path,
                 nb_classes=nb_classes)
        else:
            i = int(sample.split('.')[-2])
            for j in range(nb_classes):
                tf.reset_default_graph()
                if Y_test[i][j] == 0:
                    if 'jsma' == attack:
                        jsma(datasets=datasets,
                             sample_path=sample_path + sample,
                             target=j,
                             model_path=model_path,
                             store_path=store_path,
                             nb_classes=nb_classes)
                    if 'cw' == attack:
                        cw(datasets=datasets,
                           sample_path=sample_path + sample,
                           target=j,
                           model_path=model_path,
                           store_path=store_path,
                           nb_classes=nb_classes)
Esempio n. 9
0
from nmutant_data.cifar10 import data_cifar10
import tensorflow as tf
from nmutant_data.data import get_shape
from nmutant_util.utils_imgproc import deprocess_image_1, preprocess_image_1, deprocess_image_1

datasets = 'cifar10'
num = 10000
train_start = 0
train_end = 50000
test_start = 0
test_end = 10000

preprocess_image = preprocess_image_1
X_train, Y_train, X_test, Y_test = data_cifar10(train_start=train_start,
                                                train_end=train_end,
                                                test_start=test_start,
                                                test_end=test_end,
                                                preprocess=preprocess_image)
input_shape, nb_classes = get_shape(datasets)
sample = X_test[0:num]

models3 = ['lenet1', 'lenet4', 'lenet5']
models2 = ['vgg11', 'vgg13', 'vgg16', 'vgg19']
models1 = [
    'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152',
    'googlenet12', 'googlenet16', 'googlenet22'
]
models = [
    'vgg11', 'vgg13', 'vgg16', 'vgg19', 'resnet18', 'resnet34', 'resnet50',
    'resnet101', 'resnet152', 'googlenet12', 'googlenet16', 'googlenet22'
]
Esempio n. 10
0
def prepare_datasets(datasets, model_path, attack_type, sample_path):
    print('Loading the data and model...')
    # Load the model
    sess, preds, x, y, model, feed_dict = model_load(datasets, model_path)
    # Load the dataset
    if 'mnist' == datasets:
        train_start = 0
        train_end = 60000
        test_start = 0
        test_end = 10000

        # Get MNIST test data
        X_train, Y_train, X_test, Y_test = data_mnist(train_start=train_start,
                                                      train_end=train_end,
                                                      test_start=test_start,
                                                      test_end=test_end)
    elif 'cifar10' == datasets:
        preprocess_image = preprocess_image_1
        train_start = 0
        train_end = 50000
        test_start = 0
        test_end = 10000

        # Get CIFAR10 test data
        X_train, Y_train, fn_train, X_test, Y_test, fn_test = data_cifar10(
            train_start=train_start,
            train_end=train_end,
            test_start=test_start,
            test_end=test_end,
            preprocess=preprocess_image)

    if attack_type == "normal":
        # Refine the normal, noisy and adversarial sets to only include samples for
        # which the original version was correctly classified by the model
        preds_test = np.asarray([])
        for i in range(40):
            preds_test = np.concatenate(
                (preds_test,
                 model_argmax(sess,
                              x,
                              preds,
                              X_test[i * 250:(i + 1) * 250],
                              feed=feed_dict)))
        inds_correct = np.asarray(
            np.where(preds_test == Y_test.argmax(axis=1))[0])
        inds_correct = inds_correct[np.random.choice(len(inds_correct),
                                                     5000,
                                                     replace=False)]
        X_test = X_test[inds_correct]
        for i in range(4000):
            imsave(
                "../datasets/experiment/" + datasets + "/normal/train/" +
                str(inds_correct[i]) + '_' +
                str(int(preds_test[inds_correct[i]])) + '_' +
                str(int(preds_test[inds_correct[i]])) + '_.png',
                deprocess_image_1(X_test[i:i + 1]))
        for j in range(1000):
            imsave(
                "../datasets/experiment/" + datasets + "/normal/test/" +
                str(inds_correct[4000 + j]) + '_' +
                str(int(preds_test[inds_correct[4000 + j]])) + '_' +
                str(int(preds_test[inds_correct[4000 + j]])) + '_.png',
                deprocess_image_1(X_test[4000 + j:4001 + j]))
    elif attack_type == "error":
        preds_test = np.asarray([])
        for i in range(40):
            preds_test = np.concatenate(
                (preds_test,
                 model_argmax(sess,
                              x,
                              preds,
                              X_test[i * 250:(i + 1) * 250],
                              feed=feed_dict)))
        inds_correct = np.asarray(
            np.where(preds_test != Y_test.argmax(axis=1))[0])
        X_test = X_test[inds_correct]
        num = int(len(X_test) * 0.8)
        for i in range(num):
            imsave(
                "../datasets/experiment/" + datasets + "/error/train/" +
                str(inds_correct[i]) + '_' +
                str(int(np.argmax(Y_test[inds_correct[i]]))) + '_' +
                str(int(preds_test[inds_correct[i]])) + '_.png',
                deprocess_image_1(X_test[i:i + 1]))
        for j in range(len(X_test) - num):
            imsave(
                "../datasets/experiment/" + datasets + "/error/test/" +
                str(inds_correct[num + j]) + '_' +
                str(int(np.argmax(Y_test[inds_correct[num + j]]))) + '_' +
                str(int(preds_test[inds_correct[num + j]])) + '_.png',
                deprocess_image_1(X_test[num + j:num + 1 + j]))
    else:
        # Check attack type, select adversarial and noisy samples accordingly
        print('Loading adversarial samples...')
        # Load adversarial samplesx
        [X_test_adv, adv_image_files, real_labels, predicted_labels
         ] = utils.get_data_mutation_test(sample_path + attack_type + '/' +
                                          datasets)
        if len(X_test_adv) > 5000:
            index = np.asarray(range(len(X_test_adv)))
            index = index[np.random.choice(len(index), 5000, replace=False)]
            for i in range(4000):
                imsave(
                    "../datasets/experiment/" + datasets + "/" + attack_type +
                    "/train/" + adv_image_files[index[i]],
                    X_test_adv[index[i]])
            for j in range(1000):
                imsave(
                    "../datasets/experiment/" + datasets + "/" + attack_type +
                    "/test/" + adv_image_files[index[4000 + j]],
                    X_test_adv[index[4000 + j]])
        else:
            index = np.asarray(range(len(X_test_adv)))
            np.random.shuffle(index)
            cut = int(len(X_test_adv) * 0.8)
            for i in range(len(index)):
                if i < cut:
                    imsave(
                        "../datasets/experiment/" + datasets + "/" +
                        attack_type + "/train/" + adv_image_files[index[i]],
                        X_test_adv[index[i]])
                else:
                    imsave(
                        "../datasets/experiment/" + datasets + "/" +
                        attack_type + "/test/" + adv_image_files[index[i]],
                        X_test_adv[index[i]])