本文整理汇总了Python中cleverhans.attacks.FastGradientMethod方法的典型用法代码示例。如果您正苦于以下问题:Python attacks.FastGradientMethod方法的具体用法?Python attacks.FastGradientMethod怎么用?Python attacks.FastGradientMethod使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cleverhans.attacks
的用法示例。
在下文中一共展示了attacks.FastGradientMethod方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_feature_pairing
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def test_feature_pairing(self):
fgsm = FastGradientMethod(self.model)
attack = lambda x: fgsm.generate(x)
loss = FeaturePairing(self.model, weight=0.1, attack=attack)
l = loss.fprop(self.x, self.y)
with tf.Session() as sess:
vl1 = sess.run(l, feed_dict={self.x: self.vx, self.y: self.vy})
vl2 = sess.run(l, feed_dict={self.x: self.vx, self.y: self.vy})
self.assertClose(vl1, sum([4.296023369, 2.963884830]) / 2., atol=1e-6)
self.assertClose(vl2, sum([4.296023369, 2.963884830]) / 2., atol=1e-6)
loss = FeaturePairing(self.model, weight=10., attack=attack)
l = loss.fprop(self.x, self.y)
with tf.Session() as sess:
vl1 = sess.run(l, feed_dict={self.x: self.vx, self.y: self.vy})
vl2 = sess.run(l, feed_dict={self.x: self.vx, self.y: self.vy})
self.assertClose(vl1, sum([4.333082676, 3.00094414]) / 2., atol=1e-6)
self.assertClose(vl2, sum([4.333082676, 3.00094414]) / 2., atol=1e-6)
示例2: build_adv
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def build_adv(make_obs_tf, q_func, num_actions, epsilon, noisy):
with tf.variable_scope('deepq', reuse=tf.AUTO_REUSE):
obs_tf_in = U.ensure_tf_input(make_obs_tf("observation"))
stochastic_ph_adv = tf.placeholder(tf.bool, (), name="stochastic_adv")
update_eps_ph_adv = tf.placeholder(tf.float32, (), name="update_eps_adv")
eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0))
update_eps_expr_adv = eps.assign(tf.cond(update_eps_ph_adv >= 0, lambda: update_eps_ph_adv, lambda: eps))
print ("==========================================")
#def wrapper(x):
# return q_func(x, num_actions, scope="q_func", reuse=True, concat_softmax=True, noisy=noisy)
adversary = FastGradientMethod(q_func(obs_tf_in.get(), num_actions, scope="q_func", reuse=True, concat_softmax=True, noisy=noisy), sess=U.get_session())
adv_observations = adversary.generate(obs_tf_in.get(), eps=epsilon, clip_min=0, clip_max=1.0) * 255.0
craft_adv_obs = U.function(inputs=[obs_tf_in, stochastic_ph_adv, update_eps_ph_adv],
outputs=adv_observations,
givens={update_eps_ph_adv: -1.0, stochastic_ph_adv: True},
updates=[update_eps_expr_adv])
return craft_adv_obs
#######################
示例3: test_feature_pairing
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def test_feature_pairing(self):
sess = tf.Session()
fgsm = FastGradientMethod(self.model, sess=sess)
def attack(x):
return fgsm.generate(x)
loss = FeaturePairing(self.model, weight=0.1, attack=attack)
l = loss.fprop(self.x, self.y)
vl1 = sess.run(l, feed_dict={self.x: self.vx, self.y: self.vy})
vl2 = sess.run(l, feed_dict={self.x: self.vx, self.y: self.vy})
self.assertClose(vl1, sum([4.296023369, 2.963884830]) / 2., atol=1e-6)
self.assertClose(vl2, sum([4.296023369, 2.963884830]) / 2., atol=1e-6)
loss = FeaturePairing(self.model, weight=10., attack=attack)
l = loss.fprop(self.x, self.y)
vl1 = sess.run(l, feed_dict={self.x: self.vx, self.y: self.vy})
vl2 = sess.run(l, feed_dict={self.x: self.vx, self.y: self.vy})
self.assertClose(vl1, sum([4.333082676, 3.00094414]) / 2., atol=1e-6)
self.assertClose(vl2, sum([4.333082676, 3.00094414]) / 2., atol=1e-6)
示例4: create_adv_examples
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def create_adv_examples(model, input_t, x_to_adv, attack_dict):
"""
This fn may seem bizarre and pointless, but the point of it is to
enable the entire attack to be specified as a dict from the command line without
editing this script, which is convenient for storing the settings used for an attack
"""
if attack_dict['method'] == 'fgm':
attack = attacks.FastGradientMethod(model, sess=K.get_session(), back='tf')
elif attack_dict['method'] == 'bim':
attack = attacks.BasicIterativeMethod(model, sess=K.get_session(), back='tf')
elif attack_dict['method'] == 'mim':
attack = attacks.MomentumIterativeMethod(model, sess=K.get_session(), back='tf')
else:
assert False, 'Current attack needs to be added to the create attack fn'
adv_tensor = attack.generate(input_t, **{k: a for k, a in attack_dict.items() if
k != 'method'}) # 'method' key for this fn use
x_adv = batch_eval(adv_tensor, input_t, x_to_adv, batch_size=args.batch_size, verbose="Generating adv examples")
return x_adv
示例5: setUp
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def setUp(self):
super(TestFastGradientMethod, self).setUp()
self.sess = tf.Session()
self.model = SimpleModel()
self.attack = FastGradientMethod(self.model, sess=self.sess)
示例6: main
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def main(_):
# Images for inception classifier are normalized to be in [-1, 1] interval,
# eps is a difference between pixels so it should be in [0, 2] interval.
# Renormalizing epsilon from [0, 255] to [0, 2].
eps = 2.0 * FLAGS.max_epsilon / 255.0
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
num_classes = 1001
tf.logging.set_verbosity(tf.logging.INFO)
with tf.Graph().as_default():
# Prepare graph
x_input = tf.placeholder(tf.float32, shape=batch_shape)
model = InceptionModel(num_classes)
fgsm = FastGradientMethod(model)
x_adv = fgsm.generate(x_input, eps=eps, clip_min=-1., clip_max=1.)
# Run computation
saver = tf.train.Saver(slim.get_model_variables())
session_creator = tf.train.ChiefSessionCreator(
scaffold=tf.train.Scaffold(saver=saver),
checkpoint_filename_with_path=FLAGS.checkpoint_path,
master=FLAGS.master)
with tf.train.MonitoredSession(session_creator=session_creator) as sess:
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
adv_images = sess.run(x_adv, feed_dict={x_input: images})
save_images(adv_images, filenames, FLAGS.output_dir)
示例7: attack
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def attack(model, session, a):
fgsm = FastGradientMethod(model, sess=session)
image = a.original_image[np.newaxis]
return fgsm.generate_np(image)
示例8: __init__
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def __init__(self, model, dtypestr='float32', **kwargs):
"""
Creates a FastGradientMethod instance in eager execution.
:model: CNN network, should be an instance of
cleverhans.model.Model, if not wrap
the output to probs.
:dtypestr: datatype in the string format.
"""
del kwargs
if not isinstance(model, Model):
model = CallableModelWrapper(model, 'probs')
super(FastGradientMethod, self).__init__(model, dtypestr)
示例9: generate_fgsm_examples
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def generate_fgsm_examples(sess, model, x, y, X, Y, attack_params, verbose, attack_log_fpath):
"""
Untargeted attack. Y is not needed.
"""
fgsm = FastGradientMethod(model, back='tf', sess=sess)
fgsm_params = {'eps': 0.1, 'ord': np.inf, 'y': None, 'clip_min': 0, 'clip_max': 1}
fgsm_params = override_params(fgsm_params, attack_params)
X_adv = fgsm.generate_np(X, **fgsm_params)
return X_adv
示例10: setUp
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def setUp(self):
# Inheritance doesn't really work with tests.
# nosetests always wants to run this class because it is a
# CleverHansTest subclass, but this class is meant to just
# be abstract.
# Before this class was the tests for FastGradientMethod but
# people kept inheriting from it for other attacks so it was
# impossible to write tests specifically for FastGradientMethod.
# pylint: disable=unidiomatic-typecheck
if type(self) is CommonAttackProperties:
raise SkipTest()
super(CommonAttackProperties, self).setUp()
self.sess = tf.Session()
self.model = SimpleModel()
示例11: test_generate_respects_dtype
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def test_generate_respects_dtype(self):
self.attack = FastGradientMethod(self.model, sess=self.sess,
dtypestr='float64')
x = tf.placeholder(dtype=tf.float64, shape=(100, 2))
x_adv = self.attack.generate(x)
self.assertEqual(x_adv.dtype, tf.float64)
示例12: main
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def main(_):
"""Run the sample attack"""
# Images for inception classifier are normalized to be in [-1, 1] interval,
# eps is a difference between pixels so it should be in [0, 2] interval.
# Renormalizing epsilon from [0, 255] to [0, 2].
eps = 2.0 * FLAGS.max_epsilon / 255.0
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
nb_classes = 1001
tf.logging.set_verbosity(tf.logging.INFO)
with tf.Graph().as_default():
# Prepare graph
x_input = tf.placeholder(tf.float32, shape=batch_shape)
model = InceptionModel(nb_classes)
fgsm = FastGradientMethod(model)
x_adv = fgsm.generate(x_input, eps=eps, clip_min=-1., clip_max=1.)
# Run computation
saver = tf.train.Saver(slim.get_model_variables())
session_creator = tf.train.ChiefSessionCreator(
scaffold=tf.train.Scaffold(saver=saver),
checkpoint_filename_with_path=FLAGS.checkpoint_path,
master=FLAGS.master)
with tf.train.MonitoredSession(session_creator=session_creator) as sess:
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
adv_images = sess.run(x_adv, feed_dict={x_input: images})
save_images(adv_images, filenames, FLAGS.output_dir)
示例13: attack
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def attack(model, session, a):
fgsm = FastGradientMethod(model, sess=session)
image = a.original_image[np.newaxis]
return fgsm.generate_np(image)
示例14: __init__
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def __init__(self, model, dtypestr='float32', **kwargs):
"""
Creates a FastGradientMethod instance in eager execution.
:model: cleverhans.model.Model
:dtypestr: datatype in the string format.
"""
del kwargs
if not isinstance(model, Model):
wrapper_warning()
model = CallableModelWrapper(model, 'probs')
super(FastGradientMethod, self).__init__(model, dtypestr)
示例15: main
# 需要导入模块: from cleverhans import attacks [as 别名]
# 或者: from cleverhans.attacks import FastGradientMethod [as 别名]
def main(argv):
checkpoint = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)
if checkpoint is None:
raise ValueError("Couldn't find latest checkpoint in " +
FLAGS.checkpoint_dir)
train_start = 0
train_end = 60000
test_start = 0
test_end = 10000
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)
assert Y_train.shape[1] == 10
# NOTE: for compatibility with Madry Lab downloadable checkpoints,
# we cannot enclose this in a scope or do anything else that would
# change the automatic naming of the variables.
model = MadryMNIST()
x_input = tf.placeholder(tf.float32, shape=[None, 784])
x_image = tf.placeholder(tf.float32, shape=[None, 28, 28, 1])
y = tf.placeholder(tf.float32, shape=[None, 10])
if FLAGS.attack_type == 'fgsm':
fgsm = FastGradientMethod(model)
fgsm_params = {'eps': 0.3, 'clip_min': 0., 'clip_max': 1.}
adv_x = fgsm.generate(x_image, **fgsm_params)
elif FLAGS.attack_type == 'bim':
bim = BasicIterativeMethod(model)
bim_params = {'eps': 0.3, 'clip_min': 0., 'clip_max': 1.,
'nb_iter': 50,
'eps_iter': .01}
adv_x = bim.generate(x_image, **bim_params)
else:
raise ValueError(FLAGS.attack_type)
preds_adv = model.get_probs(adv_x)
saver = tf.train.Saver()
with tf.Session() as sess:
# Restore the checkpoint
saver.restore(sess, checkpoint)
# Evaluate the accuracy of the MNIST model on adversarial examples
eval_par = {'batch_size': FLAGS.batch_size}
t1 = time.time()
acc = model_eval(
sess, x_image, y, preds_adv, X_test, Y_test, args=eval_par)
t2 = time.time()
print("Took", t2 - t1, "seconds")
print('Test accuracy on adversarial examples: %0.4f\n' % acc)