TensorFlow的Print或K.print_tensor不在损失函数中打印中间张量 - python

我为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)

实际上,我将用我的自定义损失替换mean_squared_error。 “ mean_squared_error”将被打印,但不是我尝试使用TensorFlow打印(也不是Keras打印)打印的值。我还尝试了与How do I print inside the loss function during training in 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)

也不打印任何内容。

我是否错误使用TensorFlow的Print和Keras print_tensor?还是将结果打印在其他地方?我尝试使用print("test", file=sys.stderr)测试控制台的stderr,并获得正确的输出test

为了澄清起见,我知道您可以使用K.eval来使测试代码打印出张量的值,但是由于我无法在损失函数中使用K.eval,因此需要使tf.PrintK.print_tensor起作用。

python参考方案

这里的问题是训练代码通常实际上并不取决于损耗张量的值!通常,您无需计算损失的实际值即可计算损失的梯度,这意味着tensorflow的运行时可以自由地从图中修剪损失的实际执行情况。

您可以将损失函数包装在tf.contrib.eager.defun装饰器中,这样做的副作用是,即使您的向后传递不需要所有有状态的操作,它们也可以运行。

如何打印浮点数的全精度[Python] - python

我编写了以下函数,其中传递了x,y的值:def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" 现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:<…

python打印列表的所有子集 - python

This question already has answers here: How to get all subsets of a set? (powerset)                                                                    (18个回答)                      …

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

如何在模型内部冻结模型的特定层? - python

我的keras模型由多个模型组成。每个“子模型”都有多个层次。如何在“子模型”中调出图层并设置可训练性/冻结特定图层? python参考方案 我将使用Keras中的VGG19卷积神经网络的示例,尽管它适用于任何神经网络体系结构:from keras.applications.vgg19 import VGG19 model = VGG19(weights=&…

keras中的自定义RMSPE损失函数 - python

我正在尝试在keras中定义我自己的损失函数,即均方根百分比误差。 RMSPE定义为:我已经将损失函数定义为:from keras import backend as K def rmspe(y_true, y_pred): sum = K.sqrt(K.mean(K.square( (y_true - y_pred) / K.clip(K.abs(y_tr…