TrasorFlow会话内部Keras自定义丢失功能

时间:2018-04-06 08:02:36

标签: python tensorflow keras loss-function

在浏览了一些Stack问题和Keras文档之后,我设法编写了一些代码,试图评估神经网络输出的梯度与其输入,目的是近似双变量函数的简单练习({{ 1}})使用分析和自动区分之间的差异作为损失。

结合两个问题(Keras custom loss function: Accessing current input pattern Getting gradient of model output w.r.t weights using Keras )的答案,我提出了这个问题:

f(x,y) = x^2+y^2

由于import tensorflow as tf from keras import backend as K from keras.models import Model from keras.layers import Dense, Activation, Input def custom_loss(input_tensor): outputTensor = model.output listOfVariableTensors = model.input gradients = K.gradients(outputTensor, listOfVariableTensors) sess = tf.InteractiveSession() sess.run(tf.initialize_all_variables()) evaluated_gradients = sess.run(gradients,feed_dict={model.input:input_tensor}) grad_pred = K.add(evaluated_gradients[0], evaluated_gradients[1]) grad_true = k.add(K.scalar_mul(2, model.input[0][0]), K.scalar_mul(2, model.input[0][1])) return K.square(K.subtract(grad_pred, grad_true)) input_tensor = Input(shape=(2,)) hidden = Dense(10, activation='relu')(input_tensor) out = Dense(1, activation='sigmoid')(hidden) model = Model(input_tensor, out) model.compile(loss=custom_loss_wrapper(input_tensor), optimizer='adam') 而产生错误:TypeError: The value of a feed cannot be a tf.Tensor object.。我理解错误,我只是不知道如何解决它。

从我收集的内容来看,我不能简单地将输入数据传递给损失函数,它必须是张量。我意识到Keras会理解'我打电话给feed_dict={model.input:input_tensor}时。这一切只会让我觉得我做错了事情,试图像这样评估渐变。真的很感激一些启蒙。

2 个答案:

答案 0 :(得分:2)

我真的不明白为什么你想要这种损失功能,但无论如何我都会提供答案。此外,不需要评估函数内的梯度(实际上,您将"断开"计算图)。损失函数可以如下实现:

.intro-container {
  width: 100%;
  min-height: 400px;
  background-color: #fdee58;
  margin: 0;
  padding: 0;
}

.intro-container-text {
  width: 50%;
  margin: 0;
  padding: 0;
  min-height: 100px;
  display: inline-block;
  background-color: #ff0000;
  float: left;
}

.intro-containter-img {
  display: inline-block;
  min-height: 100px;
  width: 50%;
  margin: 0;
  padding: 0;
  background-color: #00ffff;
  float: left;
}

答案 1 :(得分:0)

Keras损失必须以y_truey_pred作为输入。在拟合期间,您可以尝试将输入对象同时添加为xy

def custom_loss(y_true,y_pred):
    ...
    return K.square(K.subtract(grad_true, grad_pred))

...
model.compile(loss=custom_loss, optimizer='adam')

model.fit(X, X, ...)

这样,y_true将是每次迭代从输入X处理的批处理,而y_pred将是该特定批处理的模型的输出。