关于#python#的问题:怎么把第一个等式变成第二个等式再变成第三个等式运行出来

img


现有第一个等式的代码

U = ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10']
C = ['a', 'b', 'c', 'e', 'f', 'g']
D = ['d']
d=[0,2,1,2,1,0,1,1,1,0]
m = [
    [0, 0, 0, 0, 0, 0],# 0],
    [1, 0, 0, 0, 0, 0],# 2],
    [0, 1, 1, 1, 1, 1],# 1],
    [0, 0, 0, 1, 0, 0],# 2],
    [0, 1, 1, 1, 0, 1],# 1],
    [0, 0, 1, 1, 0, 0],# 0],
    [0, 0, 1, 1, 0, 0],# 1],
    [0, 1, 1, 1, 0, 1],# 1],
    [0, 0, 0, 1, 0, 0],# 1],
    [1, 0, 0, 0, 0, 0],# 0]
    ]
n=[]
h=[]
for i in range(1,11):
    for z in range(i,10):
        for j in range(1, 7):
            if m[i - 1][j-1] == m[z][j-1]:
                continue
            if m[i - 1][j-1] != m[z][j-1]:
                n.append(C[j-1])
        h.append(n)
        n = []
lst = []
for el in h:
    if lst.count(el) < 1:
        lst.append(el)
lst.remove([])
print(lst)



```,怎么把第一个等式变成第二个等式再变成第三个等式运行出来

python调试三板斧 https://ask.csdn.net/questions/7908322/54130133

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/7542496
  • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:python练习44:两个 3 行 3 列的矩阵,实现其对应位置的数据相加,并返回一个新矩阵:
  • 除此之外, 这篇博客: 利用python实现深度学习生成对抗样本模型,为任一图片加扰动并恢复原像素的全流程记录中的 (二)处理图片(即生成对抗图片) 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:

    处理图片我还是使用inception_v3.ckpt这个模型,因为他生成的图片像素较大。这一段内容,我加了较多的注释,可以自行阅读。

    import tensorflow as tf
    import tensorflow.contrib.slim as slim
    import tensorflow.contrib.slim.nets as nets
    import PIL
    import numpy as np
    import tempfile
    from urllib.request import urlretrieve
    import tarfile
    import os
    from PIL import Image
    import json
    import matplotlib.pyplot as plt
    import matplotlib.image as mp
    
    #首先,设置输入图像。使用tf.Variable而不是使用tf.placeholder,这是因为要确保它是可训练的。当我们需要时,仍然可以输入它。
    tf.logging.set_verbosity(tf.logging.ERROR)
    sess = tf.InteractiveSession()
    image = tf.Variable(tf.zeros((299, 299, 3)))
    
    #加载Inception v3模型
    def inception(image, reuse):
        #multiply矩阵对应位置相乘,subtract矩阵对应位置相减,expand_dims,为0时,转变为一维函数
        preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)
        #weight_decay衰减权重
        arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)
        #arg_scope常用于为tensorflow里的layer函数提供默认值,以使构建模型的代码更加紧凑苗条(slim)
        # 定义inception-v3模型结构 inception_v3.ckpt里只有参数的取值
        with slim.arg_scope(arg_scope):
            # logits  inception_v3前向传播得到的结果
            logits, _ = nets.inception.inception_v3(
                preprocessed, 1001, is_training=False, reuse=reuse)
            logits = logits[:, 1:]  # ignore background class
            #Softmax简单的说就是把一个N*1的向量归一化为(0,1)之间的值,归一化
            probs = tf.nn.softmax(logits)  # probabilities
        return logits, probs
    
    
    logits, probs = inception(image, reuse=False)
    
    #加载预训练的权重
    data_dir = './saved_models'
    # 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()
        #startsWith()方法用来判断当前字符串是否是以另外一个给定的子字符串“开头”的,根据判断结果返回 true 或 false
        if var.name.startswith('InceptionV3/')
    ]
    
    #创建一个saver
    saver = tf.train.Saver(restore_vars)
    #恢复模型
    saver.restore(sess, os.path.join(data_dir, 'inception_v3.ckpt'))
    
    #显示图像,并对它进行分类及显示分类结果
    #是Imagenet图像的类别标注json文件
    imagenet_json, _ = urlretrieve(
        'http://www.anishathalye.com/media/2017/07/25/imagenet.json')
    with open(imagenet_json) as f:
        imagenet_labels = json.load(f)
    
    
    #创建显示界面
    def classify(img, correct_class=None, target_class=None, label='o'):
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 8))
        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]
        print(topprobs)
        barlist = ax2.bar(range(10), topprobs)
        for t in topk:
            print(topk.index(t))
            barlist[topk.index(t)].set_color('r')
        for i in topk:
            print(topk.index(i))
            barlist[topk.index(i)].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()
    
    
    #加载图像,并确保它已被正确分类
    img_path = './picture/test_adv.jpg'
    #图片类型
    # img_class = 388  # “大熊猫 giant panda”
    img = PIL.Image.open(img_path)
    #获取宽度和高度之间的最大值
    big_dim = max(img.width, img.height)
    #判断宽度是否大于高度
    wide = img.width > img.height
    #如果wide是false
    new_w = 299 if not wide else int(img.width * 299 / img.height)
    #如果wide是true
    new_h = 299 if wide else int(img.height * 299 / img.width)
    #重新设置尺寸尺寸,长宽最大值位299
    img = img.resize((new_w, new_h)).crop((0, 0, 299, 299))
    #归一化
    img = (np.asarray(img) / 255.0).astype(np.float32)
    classify(img)
    # classify(img, correct_class=img_class, label='o')
    
    #编写一个TensorFlow op进行相应的初始化
    x = tf.placeholder(tf.float32, (299, 299, 3))
    #输入可训练的对抗样本
    x_hat = image  # our trainable adversarial input
    #赋值,给x_hat赋x值
    assign_op = tf.assign(x_hat, x)
    
    #编写梯度下降步骤以最大化目标类的对数概率
    #生成4字节数组
    learning_rate = tf.placeholder(tf.float32, ())
    #生成4字节数组
    y_hat = tf.placeholder(tf.int32, ())
    #将标签信息转换成one_hot格式,方便评价
    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)
    
    #准备合成一个对抗样本。我们任意选择长臂猿作为我们的目标类
    demo_epsilon = 2.0 / 255.0  # a really small perturbation
    demo_lr = 1e-2
    #收敛次数
    demo_steps = 100
    #在数据集中的目标类的标签号,即长臂猿的标签号
    demo_target = 368  # "长臂猿gibbon"
    
    # 初始化
    # sess.run(assign_op, feed_dict={x: img})
    sess.run(assign_op, feed_dict={x: img})#使用img替换掉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})
        # 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()  # retrieve the adversarial example
    # import cv2
    # adv=cv2.resize(adv,(800,800))#大图为200*200
    # img_r=800-adv.shape[0]#第0个维度填充到200需要的像素点个数
    # img_b=800-adv.shape[1]#第1个维度填充到200需要的像素点个数
    # img_pad=np.pad(adv,((0,img_r),(0,img_b),(0,0)),'constant', constant_values=0)
    
    mp.imsave('./picture/test_adv.jpg', adv)
    classify(adv)
    

    我把利用cifar10模型进行图片生成的代码也贴在这里,如果需要,自行取用,这一段最重要的,是用到了IBM的art工具包,有调用那几个算法的方法。

    from os.path import abspath
    import sys
    import os
    import tensorflow as tf
    
    sys.path.append(abspath('.'))
    
    import keras
    import numpy as np
    import pickle
    
    import matplotlib.pyplot as plt
    plt.show()
    
    from keras.datasets import cifar10
    from keras.models import load_model
    from keras.utils import to_categorical
    from imageio import imread
    from PIL import Image
    
    from art.classifiers import KerasClassifier
    from art.attacks.evasion import FastGradientMethod
    from art.attacks.evasion import BasicIterativeMethod
    from art.attacks.evasion import SaliencyMapMethod
    from art.attacks.evasion import DeepFool
    #输入图片的路径
    input_dir = "./picture"
    #输出图片的路径
    output_dir = "./out"
    
    #生成数组的宽度维度
    image_width = 32
    #生成数组的高度维度
    image_height = 32
    #批量训练样本的数量
    batch_size = 10
    
    #设置数组
    #(样本数,行或称为高,列或称为宽,通道数)
    batch_shape = [batch_size, image_height, image_width, 3]
    
    #加载图片
    def load_images(input_dir, batch_shape,Model):
        #全填0
        images = np.zeros(batch_shape)
    
        filenames = []
        idx = 0
        batch_size = batch_shape[0]
        for filepath in sorted(tf.gfile.Glob(os.path.join(input_dir, '*.png'))):
            with tf.gfile.Open(filepath, "rb") as f:
                #归一化处理,两种方法,一种是除以255,值在[0,1]之间,一种是除以127.5-1,值在[-1,1]之间
                images[idx, :, :, :] = imread(f, pilmode='RGB').astype('float32')/255.0
                # images[idx, :, :, :] = imread(f, pilmode='RGB').astype(np.float) * 2.0 / 255.0 - 1.0
            filenames.append(os.path.basename(filepath))
            idx += 1
            if idx == batch_size:
                yield filenames, images,idx
                filenames = []
                images = np.zeros(batch_shape)
                idx = 0
        if idx > 0:
            yield filenames, images,idx
    
    #输出图片
    def save_images(images, filenames, output_dir):
        for i, filename in enumerate(filenames):
            # Images for inception classifier are normalized to be in [-1, 1] interval,
            # so rescale them back to [0, 1].
            with tf.gfile.Open(os.path.join(output_dir, filename), 'w') as f:
                img = (images[i, :, :, :] * 255.0).astype(np.uint8)
                # img = (((images[i, :, :, :] + 1.0) * 0.5) * 255.0).astype(np.uint8)
                Image.fromarray(img).save(f, format='png')
    
    #GPU内存不足,对GPU进行按需分配
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    keras.backend.tensorflow_backend.set_session(tf.Session(config=config))
    
    #加载模型
    my_model = load_model('./saved_models/cifar10_ResNet20v1_model.h5')
    
    # 加载需要处理的图片
    image_iterator = load_images(input_dir, batch_shape,my_model)
    
    # 得到第一个batch的图片
    filenames, images ,idx= next(image_iterator)
    
    #根据模型,生成分类器
    classifier = KerasClassifier( model=my_model)
    
    # Craft adversarial samples with FGSM,加扰动
    epsilon = 0.03  # Maximum perturbation
    adv_fgsm_crafter = FastGradientMethod(classifier)
    x_test_adv_fgsm = adv_fgsm_crafter.generate(x=images, eps=epsilon)
    
    # Craft adversarial samples with IGSM
    # epsilon = 0.015  # Maximum perturbation
    # stepsize = 0.005
    # adv_igsm_crafter = BasicIterativeMethod(classifier, eps=epsilon, eps_step=stepsize)
    # x_test_adv_igsm = adv_igsm_crafter.generate(x=images)
    
    
    #显示干扰前后的图片
    fig = plt.figure(figsize=(idx, 2))
    columns = idx
    rows = 2
    for i in range(0, idx):
        img = images[i].reshape(32, 32, 3)
        fig.add_subplot(rows, columns, i+1)
        plt.imshow(img)
        plt.axis('off')
        #判断类别
        y_pred = my_model.predict(images[i].reshape(1, 32, 32, 3))
        print(np.argmax(y_pred), end=' ')
    
    for i in range(0, idx):
        img_adv = x_test_adv_fgsm[i].reshape(32, 32, 3)
        fig.add_subplot(rows, columns, i+idx+1)
        plt.imshow(img_adv)
        plt.axis('off')
        # 判断类别
        y_pred = my_model.predict(x_test_adv_fgsm[i].reshape(1, 32, 32, 3))
        print(np.argmax(y_pred), end=' ')
    
    plt.show()
    
    #保存为图片
    save_images(x_test_adv_fgsm, filenames, output_dir)
    
  • 您还可以看一下 刘建萍老师的Python实战开发之互联网电商项目的支付宝支付案例课程中的 到支付宝开发平台注册账号申请支付产品小节, 巩固相关知识点

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^