Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def main():
keras.backend.set_image_dim_ordering('th')
# We can't use argparse in a test because it reads the arguments to nosetests
# e.g., nosetests -v passes the -v to the test
args = {
"batch_size": 128,
"nb_epochs": 2,
"learning_rate": .5
}
# Get MNIST test data
X_train, Y_train, X_test, Y_test = data_mnist()
X_train = X_train[:10000]
Y_train = Y_train[:10000]
X_test = X_test[:2000]
Y_test = Y_test[:2000]
assert Y_train.shape[1] == 10.
label_smooth = .1
Y_train = Y_train.clip(label_smooth / 9., 1. - label_smooth)
# Define input Theano placeholder
x_shape = (None, 1, 28, 28)
x = T.tensor4('x')
y = T.matrix('y')
# Define Theano model graph
model = cnn_model()
def setUp(self):
# Image dimensions ordering should follow the Theano convention
if keras.backend.image_dim_ordering() != 'tf':
keras.backend.set_image_dim_ordering('tf')
print("INFO: '~/.keras/keras.json' sets 'image_dim_ordering' "
"to 'th', temporarily setting to 'tf'")
# Create TF session and set as Keras backend session
self.sess = tf.Session()
keras.backend.set_session(self.sess)
# Get MNIST test data
X_train, Y_train, self.X_test, self.Y_test = data_mnist()
label_smooth = .1
Y_train = Y_train.clip(label_smooth / 9., 1. - label_smooth)
# Define input TF placeholder
self.x = tf.placeholder(tf.float32, shape=(None, 28, 28, 1))
self.y = tf.placeholder(tf.float32, shape=(None, 10))
# Define TF model graph
self.model = model_mnist()
self.predictions = self.model(self.x)
print("Defined TensorFlow model graph.")
def evaluate():
# Evaluate the accuracy of the MNIST model on legitimate test examples
accuracy = model_eval(self.sess, self.x, self.y, self.predictions, self.X_test, self.Y_test)
def test_attacks(data_name, model_name, attack_method, eps, batch_size=100,
targeted=False, save=False):
# Set TF random seed to improve reproducibility
tf.set_random_seed(1234)
# Create TF session
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
print("Created TensorFlow session.")
set_log_level(logging.DEBUG)
if data_name == 'mnist':
from cleverhans.utils_mnist import data_mnist
X_train, Y_train, X_test, Y_test = data_mnist(train_start=0, train_end=60000,
test_start=0, test_end=10000)
if data_name in ['cifar10', 'plane_frog']:
from import_data_cifar10 import load_data_cifar10
if data_name == 'plane_frog':
labels = [0, 6]
else:
labels = None
data_path = '../cifar_data/'
X_train, X_test, Y_train, Y_test = load_data_cifar10(data_path, labels=labels, conv=True)
source_samples, img_rows, img_cols, channels = X_test.shape
nb_classes = Y_test.shape[1]
# test cw
#source_samples = 100
# Define input TF placeholder
:param batch_size: size of training batches
:param learning_rate: learning rate for training
:return: an AccuracyReport object
"""
batch_size = hparams.batch_size
# Set TF random seed to improve reproducibility
tf.set_random_seed(1234)
# Create TF session
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
if FLAGS.dataset == 'mnist':
# Get MNIST test data
X_train, Y_train, X_test, Y_test = data_mnist()
input_shape = (batch_size, 28, 28, 1)
preproc_func = None
elif FLAGS.dataset == 'cifar10':
X_train, Y_train, X_test, Y_test = cifar_input.read_CIFAR10(
_data_path[FLAGS.dataset])
input_shape = (batch_size, 32, 32, 3)
preproc_func = cifar_input.cifar_tf_preprocess
# Define input TF placeholder
x_pre = tf.placeholder(tf.float32, shape=input_shape, name='x')
x = preprocess_batch(x_pre, preproc_func)
y = tf.placeholder(tf.float32, shape=(batch_size, 10), name='y')
# Use label smoothing
assert Y_train.shape[1] == 10.
label_smooth = .1
if not hasattr(backend, "tf"):
raise RuntimeError("This tutorial requires keras to be configured"
" to use the TensorFlow backend.")
# Image dimensions ordering should follow the Theano convention
if keras.backend.image_dim_ordering() != 'tf':
keras.backend.set_image_dim_ordering('tf')
print("INFO: '~/.keras/keras.json' sets 'image_dim_ordering' to "
"'th', temporarily setting to 'tf'")
# Create TF session and set as Keras backend session
sess = tf.Session()
keras.backend.set_session(sess)
# 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)
# Use label smoothing
assert Y_train.shape[1] == 10
label_smooth = .1
Y_train = Y_train.clip(label_smooth / 9., 1. - label_smooth)
# Define input TF placeholder
x = tf.placeholder(tf.float32, shape=(None, 28, 28, 1))
y = tf.placeholder(tf.float32, shape=(None, 10))
# Define TF model graph
model = cnn_model()
preds = model(x)
"""
keras.layers.core.K.set_learning_phase(0)
# Dictionary used to keep track and return key accuracies
accuracies = {}
# Perform tutorial setup
assert setup_tutorial()
# Create TF session and set as Keras backend session
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.45)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
keras.backend.set_session(sess)
# Get MNIST 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)
# Initialize substitute training set reserved for adversary
X_sub = X_test[:holdout]
Y_sub = np.argmax(Y_test[:holdout], axis=1)
# Redefine test set as remaining samples unavailable to adversaries
X_test = X_test[holdout:]
Y_test = Y_test[holdout:]
X_test = X_test[:FLAGS.n_attack]
Y_test = Y_test[:FLAGS.n_attack]
# Define input and output TF placeholders
keras.layers.core.K.set_learning_phase(0)
# Dictionary used to keep track and return key accuracies
accuracies = {}
# Perform tutorial setup
assert setup_tutorial()
# Create TF session and set as Keras backend session
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1.0)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
keras.backend.set_session(sess)
# Get MNIST data
if DATASET == "mnist":
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)
else:
X_train, Y_train, X_test, Y_test = data_cifar10()
# Initialize substitute training set reserved for adversary
X_sub = X_test[:holdout]
Y_sub = np.argmax(Y_test[:holdout], axis=1)
# Redefine test set as remaining samples unavailable to adversaries
X_test = X_test[holdout:]
Y_test = Y_test[holdout:]
X_test = X_test[:FLAGS.n_attack]
Y_test = Y_test[:FLAGS.n_attack]
# MNIST-specific dimensions
img_rows = 28
img_cols = 28
channels = 1
# Set TF random seed to improve reproducibility
tf.set_random_seed(1234)
# Create TF session
sess = tf.Session()
print("Created TensorFlow session.")
set_log_level(logging.DEBUG)
# 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)
# Define input TF placeholder
x = tf.placeholder(tf.float32, shape=(None, 28, 28, 1))
y = tf.placeholder(tf.float32, shape=(None, 10))
# Define TF model graph
model = make_basic_cnn()
preds = model(x)
print("Defined TensorFlow model graph.")
###########################################################################
# Training the model using TensorFlow
###########################################################################
if not hasattr(backend, "tf"):
raise RuntimeError("This tutorial requires keras to be configured"
" to use the TensorFlow backend.")
# Image dimensions ordering should follow the Theano convention
if keras.backend.image_dim_ordering() != 'tf':
keras.backend.set_image_dim_ordering('tf')
print("INFO: '~/.keras/keras.json' sets 'image_dim_ordering' to "
"'th', temporarily setting to 'tf'")
# Create TF session and set as Keras backend session
sess = tf.Session()
keras.backend.set_session(sess)
# Get MNIST test data
X_train, Y_train, X_test, Y_test = data_mnist()
assert Y_train.shape[1] == 10.
label_smooth = .1
Y_train = Y_train.clip(label_smooth / 9., 1. - label_smooth)
# Define input TF placeholder
x = tf.placeholder(tf.float32, shape=(None, 28, 28, 1))
y = tf.placeholder(tf.float32, shape=(None, 10))
# Define TF model graph
model = cnn_model()
predictions = model(x)
print("Defined TensorFlow model graph.")
saver = tf.train.Saver()
save_path = os.path.join(FLAGS.train_dir, FLAGS.filename)