Ejemplo n.º 1
0
import scipy.io as sio
import numpy as np
import keras
from models.vae import vae_model_cifar, vae_model_mnist
from loaddata import load_mnist
from keras import backend as K
import tensorflow as tf
from data.data import load_cifar
from jpeg import rgb_to_ycbcr

# MNIST
X_train, Y_train, X_test, Y_test, labels_train, labels_test = load_mnist()

# CIFAR
# Load dataset
train_x, train_y, train_l = load_cifar()
test_x, test_y, test_l = load_cifar("test")

# Reshape
train_x = train_x.reshape([-1, 32, 32, 3])
test_x = test_x.reshape([-1, 32, 32, 3])

# Create TF session and set as Keras backend session
sess = tf.Session()
keras.backend.set_session(sess)

vae_cifar = vae_model_cifar()
vae_mnist = vae_model_mnist()

vae_cifar.compile(optimizer='adam')
vae_mnist.compile(optimizer='adam')
Ejemplo n.º 2
0
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import kmeans
from sklearn import tree
import pca
import loaddata as ld
import arraycut as ac
from sklearn.svm import SVC

X_train, y_train = ld.load_mnist("MNIST_data/", kind="train")
X_test, y_test = ld.load_mnist("MNIST_data/", kind="t10k")
X_train = X_train[:20000]
mt = X_train.shape[0]
y_train = y_train[:20000]
X_test = X_test[:20000]
y_test = y_test[:20000]
ms = X_test.shape[0]


def init(x_train):  # 进行数据预处理
    u = np.mean(x_train, axis=0)  # 计算均值
    s = np.std(x_train, axis=0)
    x_train = (x_train - u) / s
    return x_train


"""
x_train_cut,label_x=ac.randomcut(X_train,5,y_train)
x_test_cut,label_y=ac.rulecut(X_test,y_test)
x_train_cut=x_train_cut.reshape(x_train_cut.shape[0]*x_train_cut.shape[1],x_train_cut.shape[2]*x_train_cut.shape[3])
Ejemplo n.º 3
0
    reconstruction = decoder(encoder(adv_images)[2])
    vae = Model([adv_images, clean_images, labels], reconstruction, name='VAE')

    reconstruction_loss = K.sum(keras.losses.binary_crossentropy(
        clean_images, reconstruction),
                                axis=-1)
    reconstruction_loss *= 784

    kl_loss = 1 + z_log_sigma - K.square(z_mean) - K.exp(z_log_sigma)
    kl_loss = K.sum(kl_loss, axis=-1)
    kl_loss *= -0.5

    print(reconstruction.shape)
    y_pred = classifier.predict(reconstruction)
    print(y_pred.shape)
    model_loss = K.sum(keras.losses.categorical_crossentropy(labels, y_pred),
                       axis=-1)
    vae_loss = K.mean(reconstruction_loss + kl_loss + model_loss)
    vae.add_loss(vae_loss)

    return vae


x_train, y_train, x_test, y_test = load_mnist()
x_train_adv = x_train.copy()

model = DefenseVAE()
model.compile(optimizer='adam')

model.fit([x_train_adv, x_train, y_train], epochs=30, batch_size=128)