Leo*_*eed 5 python keras tensorflow
我为 Keras 模型编写了一个相当复杂的损失函数,它nan在训练时不断返回。因此,我需要在训练时打印中间张量。我知道您不能在损失函数中执行 K.eval,因为张量未初始化。但是,我已经尝试过K.print_tensor(),tf.Print()并且都没有奏效。
我几乎想做这样的事情:
def mean_squared_error(y_true, y_pred):
print("mean_squared_error")
loss = K.mean(K.square(y_pred - y_true), axis=-1)
loss = tf.Print(loss, [loss])
return loss
model.compile(optimizer=self.optimizer, loss=mean_squared_error)
Run Code Online (Sandbox Code Playgroud)
在实践中,我会mean_squared_error用我的自定义损失替换。“mean_squared_error”会被打印出来,但不会打印我尝试使用 TensorFlow 打印(也不是 Keras 打印)打印的值。我还尝试了与如何在 Keras 训练期间在损失函数内部打印完全相同的代码?我仍然没有看到控制台中打印出任何内容。
另外,我写了一个单独的文件来测试一些东西。
import tensorflow as tf
import keras.backend as K
input1 = K.constant(1)
input2 = K.constant(2)
input3 = K.constant(3)
node1 = tf.add(input1, input2)
print_output = K.print_tensor(node1)
output = tf.multiply(print_output, input3)
Run Code Online (Sandbox Code Playgroud)
也没有打印任何内容。
我是否错误地使用了 TensorFlowPrint和 Keras print_tensor?或者结果打印在其他地方?我尝试使用我的控制台测试 stderrprint("test", file=sys.stderr)并获得正确的输出test。
为了澄清起见,我知道您可以使用K.eval使测试代码打印出张量的值,但由于我无法K.eval在我的损失函数中使用,我需要制作tf.Print或K.print_tensor工作。
这里的问题是训练代码通常实际上并不依赖于损失张量的值!通常,您可以计算损失的梯度,而无需计算损失的实际值,这意味着张量流的运行时可以自由地从图中删除损失的实际执行。
您可以将损失函数包装在tf.contrib.eager.defun装饰器中,它的副作用是保证函数中的所有有状态操作都运行,即使向后传递不需要它们。
| 归档时间: |
|
| 查看次数: |
2660 次 |
| 最近记录: |