在经历了一些Stack问题和Keras文档之后,我设法编写了一些代码,试图评估神经网络输出的渐变与其输入,目的是使用一个简单的近似二元函数( f(x,y) = x^2+y^2
)的运算作为损失分析和自动差异之间的区别 .
结合两个问题(Keras custom loss function: Accessing current input pattern和Getting gradient of model output w.r.t weights using Keras)的答案,我想出了这个:
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')
由于 feed_dict={model.input:input_tensor}
,产生错误: TypeError: The value of a feed cannot be a tf.Tensor object.
. 我理解错误,我只是不知道如何解决它 .
从我收集的内容来看,当我拨打 input_tensor
时,我可以理解它 . 这一切只是让我觉得我做错了方法,试图像这样评估渐变 . 真的很感激一些启蒙 .
2 回答
我真的不明白为什么你想要这种损失功能,但无论如何我都会提供一个答案 . 此外,无需评估函数内的梯度(事实上,您将“断开”计算图形) . 损失函数可以实现如下:
Keras损失必须具有
y_true
和y_pred
作为输入 . 您可以尝试在拟合期间将输入对象添加为x
和y
:这样,
y_true
将是从输入X
每次迭代处理的批处理,而y_pred
将是该特定批处理的模型的输出 .