如何在深梦中定义损失函数,例如模型输入上的渐变体面

时间:2018-11-02 14:50:45

标签: python tensorflow keras

所以我在python Kearns / Tensorflow中有一个训练有素的顺序模型(分类程序),我有一些输入。我想优化输入以最大化类别命中率。

import tensorflow as tf
import numpy as np

def dream(input, model, iterations, learning_rate):
    target = model.predict(input)
    var = tf.Variable("var", Input.shape)
    loss = np.linalg.norm(model.predict(var)-goal)
    for i in range(iterations):
        input -= learning_rate * tf.gradients(loss,input)
    return input

但是,这不起作用。

如何正确定义损失?

1 个答案:

答案 0 :(得分:0)

在看不到代码其余部分的情况下很难确切地说出问题所在,因此这将基于一些假设。

  1. 首先,这是一个问题,您打算学习可变输入图像以产生更适合几种类别之一的模型输出。
  2. 第二个原因是model.predict()函数是指定的here函数。
  3. 第三,goal是将修改后的输入图像理想地分类为在修改之前对其进行最强烈分类的类。
  4. 第四点是参数image已实例化为变量数据类型。

如果所有这些都是正确的,那么看来您正在寻找的是一种定义损失函数的方法,该函数将一组logit与一组标签进行比较。在这种情况下,诸如tf.keras.metrics.categorical_crossentropy()之类的函数应该为您完成此任务。使用基于numpy运算的损失函数将不起作用,因为numpy缺少反向传播功能所需的渐变处理功能。请仅tf.起作用。

但是,如果您说“ var具有shape()”,那么这不太可能起作用。可能是因为您使用Input.shape()进行了定义,所以传递给函数的参数称为input(情况肯定很重要)。

请参阅以下内容,对您的代码进行粗略的调整,使其看起来似乎合理。


def dream(input, model, iterations, learning_rate):
    # decide into which class your input should fit
    target = model.predict(input)
    # create ideal output of classification (1 for target class, 0 for others)
    goal = tf.one_hot(indices=tf.cast(target, tf.int32), depth=1)
    # define loss according to the cross entropy of the model prediciton vs goal
    loss =  tf.keras.metrics.categorical_crossentropy(model.predict(input), goal)
    # iterateively modify the image according to the gradients produced by 
    # differentiating the loss with respect to the variable image pixels
    for i in range(iterations):
        input -= learning_rate * tf.gradients(loss,input)
    return input

# SETUP
original_image = tf.keras.Input(shape=(a,b,3))         
input = tf.Variable(original_image, "variable_image")  # create trainable image

# add some layers
x = tf.keras.layers.Dense(n_layers, activation=tf.nn.relu)(input)
output = tf.keras.layers.Dense(n_categories, activation=tf.nn.softmax)(x)
# link model
model = tf.keras.Model(inputs=input, outputs=output)

# call function
dream(input, model, iterations, learning_rate)

注意:该代码是一个假设框架,基于对代码预期用途的假设。 此代码未经测试,不能原样运行