zoukankan      html  css  js  c++  java
  • 20155219付颖卓毕业设计-代码理解

    选择攻击在ImageNet数据集上训练的Inception v3网络。首先我们从TF-slim图像分类库中加载预先训练的网络。

    import tensorflow as tf
    import tensorflow.contrib.slim as slim
    import tensorflow.contrib.slim.nets as nets
    
    tf.logging.set_verbosity(tf.logging.ERROR)
    sess = tf.InteractiveSession()
    

    加载预设部分

    设置输入图像。使用tf.Variable而不是使用tf.placeholder,这是因为要确保它是可训练的。当我们需要时,仍然可以输入它。

    image = tf.Variable(tf.zeros((299, 299, 3)))
    

    height = 299 width = 299 channels = 3,这是Inception v3模型规定的图片大小

    接下来,加载Inception v3模型

    def inception(image, reuse):
        preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)
        arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)
        with slim.arg_scope(arg_scope):                             #  slim是一种轻量级的tensorflow库,可以使模型的构建,训练,测试都变得更加简单。
    	                                                            #在slim库中对很多常用的函数进行了定义,slim.arg_scope()是slim库中经常用到的函数之一。
    	                                                            #定义inception-v3模型结构 inception_v3.ckpt里只有参数的取值
            logits, _ = nets.inception.inception_v3(                #logits  inception_v3前向传播得到的结果
                preprocessed, 1001, is_training=False, reuse=reuse)
            logits = logits[:,1:]                                   # 忽略背景类的影响
            probs = tf.nn.softmax(logits)                           # logits就是神经网络的输出 ,转换到softmax函数之后输出结果
    		
    		                                                        #用 slim.arg_scope()为目标函数设置默认参数.
        return logits, probs
        logits, probs = inception(image, reuse=False)
    

    接下来,加载预训练的权重。从文献中看到这个Inception v3的top-5的准确率为93.9%

    import tempfile
    from urllib.request import urlretrieve
    import tarfile
    import os
    data_dir = tempfile.mkdtemp()
    inception_tarball, _ = urlretrieve(
        'http://download.tensorflow.org/models/inception_v3_2016_08_28.tar.gz')
    tarfile.open(inception_tarball, 'r:gz').extractall(data_dir)
    restore_vars = [
        var for var in tf.global_variables()
        if var.name.startswith('InceptionV3/')
    ]#使用ckpt文件中提供的参数
    saver = tf.train.Saver(restore_vars)
    saver.restore(sess, os.path.join(data_dir, 'inception_v3.ckpt'))
    
    #saver()与restore()只是保存了session中的相关变量对应的值,并不涉及模型的结构。
    #sess: 保存参数的会话。
    #save_path: 保存参数的路径。
    #当从文件中恢复变量时,不需要事先对他们进行初始化,因为“恢复”自身就是一种初始化变量的方法。
    #可以使用tf.train.latest_checkpoint()来自动获取最后一次保存的模型。
    
    
    #**Saver的作用是将我们训练好的模型的参数保存下来,以便下一次继续用于训练或测试;Restore则是将训练好的参数提取出来。Saver类训练完后,是以checkpoints文件形式保存。提取的时候也是从checkpoints文件中恢复变量。Checkpoints文件是一个二进制文件,它把变量名映射到对应的tensor值 。
    
    
    

    接下来,编写一些代码来显示图像,并对它进行分类及显示分类结果。

    import json
    import matplotlib.pyplot as plt
    imagenet_json, _ = urlretrieve(
        'http://www.anishathalye.com/media/2017/07/25/imagenet.json')
    with open(imagenet_json) as f:
        imagenet_labels = json.load(f)#引入图像的不同类别,json文件中保存着inception v3模型训练的不同结果
    def classify(img, correct_class=None, target_class=None):
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 8))#建立一个fig对象,建立两个axis对象(返回它的子图对象)如,设置 figsize=(21, 12) ,则设置了图像大小。
        fig.sca(ax1)#画函数图像
        p = sess.run(probs, feed_dict={image: img})[0]
        ax1.imshow(img) #进行图形的分辨
        fig.sca(ax1)
        
        topk = list(p.argsort()[-10:][::-1])
        topprobs = p[topk]
        barlist = ax2.bar(range(10), topprobs)
        if target_class in topk:
            barlist[topk.index(target_class)].set_color('r')
        if correct_class in topk:
            barlist[topk.index(correct_class)].set_color('g')
        plt.sca(ax2)
        plt.ylim([0, 1.1])
        plt.xticks(range(10),
                   [imagenet_labels[i][:15] for i in topk],
                   rotation='vertical')
        fig.subplots_adjust(bottom=0.2)
        plt.show()
    #形成柱状图
    

    plt.subplots函数的标注效果:

    image

    加载示例图像,并确保它已被正确分类。

    import PIL
    import numpy as np
    img_path, _ = urlretrieve('http://www.anishathalye.com/media/2017/07/25/cat.jpg')
    img_class = 281
    img = PIL.Image.open(img_path)
    big_dim = max(img.width, img.height)
    wide = img.width > img.height
    new_w = 299 if not wide else int(img.width * 299 / img.height)
    new_h = 299 if wide else int(img.height * 299 / img.width)
    img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))
    img = (np.asarray(img) / 255.0).astype(np.float32)
    
    #对图像的大小以及格式进行调整,形成适应inception v3模型的格式及大小
    classify(img, correct_class=img_class)
    

    输出结果如下:
    image

    生成fgsm对抗样本

    给定一个图像X,神经网络输出标签上的概率分布为P(y|X)。当手工制作对抗输入时,我们想要找到一个X',使得logP(y'|X')被最大化为目标标签y',即输入将被错误分类为目标类。通过进行约束,要求‖X- X'‖≤ε,我们可以确保X'与原始X看起来一样,但实际却可以达成扰乱效果。

    首先从最简单的部分开始:编写一个TensorFlow op进行相应的初始化。

    x = tf.placeholder(tf.float32, (299, 299, 3))
    
    x_hat = image 
    assign_op = tf.assign(x_hat, x)#把x的值赋给x_hat
    

    接下来,编写梯度下降步骤,以最大化目标类的成功概率

    learning_rate = tf.placeholder(tf.float32, ())
    y_hat = tf.placeholder(tf.int32, ())
    #tf.placeholder用于定义
    labels = tf.one_hot(y_hat, 1000)
    loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=[labels])
    optim_step = tf.train.GradientDescentOptimizer(
        learning_rate).minimize(loss, var_list=[x_hat])
    

    编写投影步骤,使得对抗样本在视觉上与原始图像相似。另外,将其限定为[0,1]范围内,用来保持有效的图像。

    epsilon = tf.placeholder(tf.float32, ())
    
    below = x - epsilon
    above = x + epsilon
    projected = tf.clip_by_value(tf.clip_by_value(x_hat, below, above), 0, 1)
    with tf.control_dependencies([projected]):
        project_step = tf.assign(x_hat, projected)#把project的值赋给x_hat
    

    最后,准备合成一个对抗样本。我们任意选择“鳄梨酱”(imagenet class 924)作为我们的目标类。

    demo_epsilon = 2.0/255.0 #很小的扰动
    demo_lr = 1e-1
    demo_steps = 100
    demo_target = 924 # "guacamole"
    
    # initialization step
    sess.run(assign_op, feed_dict={x: img})
    
    # projected gradient descent
    for i in range(demo_steps):
        # 梯度下降步骤
        _, loss_value = sess.run(
            [optim_step, loss],
            feed_dict={learning_rate: demo_lr, y_hat: demo_target})#引用demo_lr = 1e-1为学习率,将y_hat:设置为demo_target从而开始反向梯度下降
        # project step
        sess.run(project_step, feed_dict={x: img, epsilon: demo_epsilon})#将图像加入小的扰动
        if (i+1) % 10 == 0:
            print('step %d, loss=%g' % (i+1, loss_value))
        
    
    adv = x_hat.eval() # eval()是程序语言中的函数,功能是获取返回值,不同语言大同小异,函数原型是返回值 = eval( codeString ),如果eval函数在执行时遇到错误,则抛出异常给调用者。
    	
    
  • 相关阅读:
    71)PHP,使用cookie的语法问题
    70)PHP,cookie的安全传输和HTTPonly
    69)PHP,cookie的有效域
    68)PHP,cookie的详细属性和有效期
    C#中的internal关键字
    C# 中如何将一个类文件(XX.CS)封装成.dll文件
    c# 委托和事件(总结篇)
    c#事件实例三
    c#事件实例二
    c#事件实例一
  • 原文地址:https://www.cnblogs.com/paypay/p/10738973.html
Copyright © 2011-2022 走看看