使用保存的tensorflow模型预测图像并对图像运行攻击

2024-06-16 10:12:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Tensorflow(完全训练的imagenet预训练模型)的预训练模型,采用inception\u resnet_v2网络架构。现在,我使用傻瓜箱对医学图像使用对抗性攻击并得到预测。在

但是每次模型返回一个不同的预测值(一个具有不同概率的不同类)图像。Am我重新初始化了重量?而且,对敌对图像的预测不起作用,每次都会抛出一个非类型错误,我无法使用任何攻击。在

import tensorflow as tf
import numpy as np
from PIL import Image
from nets import nets_factory
import matplotlib.pyplot as plt

image = np.asarray(Image.open('1.jpg'))
data_tf = tf.convert_to_tensor(image, np.float32)
data_tf = tf.reshape(data_tf, [1, 299, 299, 3])
arg_scope = nets_factory.arg_scopes_map['inception_resnet_v2']()

graph = tf.get_default_graph()
with slim.arg_scope(arg_scope):
(logits, end_points) = \
    nets_factory.networks_map['inception_resnet_v2'](inputs=data_tf, num_classes=2, is_training=False)

with foolbox.models.TensorFlowModel(data_tf, logits, (0, 255)) as model:
    init_op = tf.global_variables_initializer()
    model.session.run(init_op)
    attack = foolbox.attacks.FGSM(model)
    saver = tf.train.import_meta_graph(
    '/local-scratch/arkadeep/1_June/tf_classification/experiment/final_model/model.ckpt-30589.meta',
    clear_devices=True)
    saver.restore(model.session,
              '/local-scratch/arkadeep/1_June/tf_classification/experiment/final_model/model.ckpt-30589')

    example_label = np.argmax(model.predictions(image))
    print(example_label)
    print(foolbox.utils.softmax(model.predictions(image))[0])

    adversarial = attack(image, example_label, unpack=False)
    print(np.argmax(model.predictions(adversarial.image)))
    print(foolbox.utils.softmax(model.predictions(adversarial))[0])

    print(adversarial.distance)

这是堆栈跟踪

^{pr2}$

Tags: 模型imageimportdatamodeltfasnp