如何打印Keras张量的值?

2024-05-19 06:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在实现自己的Keras损失函数。如何访问张量值?

我试过的

def loss_fn(y_true, y_pred):
    print y_true

它印出来了

Tensor("target:0", shape=(?, ?), dtype=float32)

是否有任何Keras函数可以访问y_true值?


Tags: 函数truetargetdefkerasfntensorprint
3条回答

如果使用TensorFlow的keras,则可以启用Eager Execution

import tensorflow as tf 
tf.enable_eager_execution()

然后你可以在损失函数中打印张量。

如果您收到错误消息“ValueError:Only TF native optimizer s are supported In Eager mode.”并且您使用了“adam”作为优化器,例如,您可以将模型的编译参数更改为

model.compile(optimizer = tf.train.AdamOptimizer(), loss = loss_fn, ...)

通常,y_true你事先知道-在准备你的火车语料库。。。

但是,有一个技巧可以看到y_true和/或y_pred中的值。Keras给了你一个机会写下相应的callback来打印神经网络的输出。 它看起来像这样:

def loss_fn(y_true, y_pred):
    return y_true # or y_pred
...
import keras.callbacks as cbks
class CustomMetrics(cbks.Callback):

    def on_epoch_end(self, epoch, logs=None):
        for k in logs:
            if k.endswith('loss_fn'):
               print logs[k]

这里的loss_fn是在模型编译期间将loss函数传递到model.compile(...,metrics=[loss_fn],)函数时的函数名。

因此,最后,必须将这个CustomMetrics回调作为参数传递到model.fit()

model.fit(x=train_X, y=train_Y, ... , callbacks=[CustomMetrics()])

注:如果你在Keras中使用类似于这里的Theano(或TensorFlow),你可以编写一个python程序,然后编译并执行它。因此,在您的示例中y_true-只是一个张量变量,用于进一步编译和损失函数计数。

这意味着无法看到里面的值。例如,在ano中,您可以在执行相应的eval()函数之后查看唯一所谓的共享变量。有关详细信息,请参见this question

Keras的后端有print_tensor,这使您能够做到这一点。你可以这样使用它:

import keras.backend as K

def loss_fn(y_true, y_pred):
    y_true = K.print_tensor(y_true, message='y_true = ')
    y_pred = K.print_tensor(y_pred, message='y_pred = ')
    ...

函数返回一个相同的张量。当对该张量求值时,它将打印其内容,前面是message。 从Keras docs

Note that print_tensor returns a new tensor identical to x which should be used in the following code. Otherwise the print operation is not taken into account during evaluation.

所以,以后一定要用张量。

相关问题 更多 >

    热门问题