Python 如何打印 Keras 张量的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43448029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:05:14  来源:igfitidea点击:

How can I print the values of Keras tensors?

pythonneural-networkkerastensor

提问by ronroo

I am implementing own Keras loss function. How can I access tensor values?

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

What I've tried

我试过的

def loss_fn(y_true, y_pred):
    print y_true

It prints

它打印

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

Is there any Keras function to access y_truevalues?

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

回答by nroulet

Keras' backend has print_tensorwhich enables you to do this. You can use it this way:

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 = ')
    ...

The function returns an identical tensor. When that tensor is evaluated, it will print its content, preceded by message. From the Keras docs:

该函数返回一个相同的张量。当计算该张量时,它将打印其内容,以message. 来自Keras 文档

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.

请注意,print_tensor 返回一个与 x 相同的新张量,它应该在以下代码中使用。否则在评估期间不考虑打印操作。

So, make sure to use the tensor afterwards.

因此,请确保之后使用张量。

回答by Igor Poletaev

Usually, y_trueyou know in advance - during preparation of your train corpora...

通常,y_true您事先知道 - 在准备您的火车语料库期间...

However, there's one trick to see the values inside y_trueand/or y_pred. Keras gives you an opportunity to write respective callbackfor printing the neural network's output. It will look something like this:

但是,有一个技巧可以查看y_true和/或中的值y_pred。Keras 为您提供了编写相应回调以打印神经网络输出的机会。它看起来像这样:

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]

Here the loss_fnis name of your loss function when you pass it into the model.compile(...,metrics=[loss_fn],)function during model's compilation.

loss_fnmodel.compile(...,metrics=[loss_fn],)在模型编译期间将损失函数传递给函数时的损失函数名称。

So, finally, you have to pass this CustomMetricscallback as the argument into the model.fit():

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

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

P.S.: If you use Theano (or TensorFlow) like here in Keras, you write a python program, and then you compile it and execute. So, in your example y_true- is just a tensor variable which is used for further compilation and loss function counting.

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

It means that there's no way to see the values inside it. In Theano, for example, you can look inside the only so-called shared variable after the execution of respective eval()function. See this questionfor more info.

这意味着无法看到其中的值。例如,在 Theano 中,您可以在执行相应eval()函数后查看唯一所谓的共享变量。有关更多信息,请参阅此问题

回答by F1refly

If you are using TensorFlow's keras, you can enable Eager Execution:

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

import tensorflow as tf 
tf.enable_eager_execution()

Afterwards you can print the tensors in your loss function.

之后,您可以在损失函数中打印张量。

In case you get the error message "ValueError: Only TF native optimizers are supported in Eager mode." and you have used 'adam' as an optimizer for example, you can change the model's compile arguments to

如果您收到错误消息“ValueError:Eager 模式下仅支持 TF 本机优化器”。例如,您已经使用“adam”作为优化器,您可以将模型的编译参数更改为

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

回答by Raimi bin Karim

You could redefine your loss function to return the value instead:

您可以重新定义损失函数以返回值:

def loss_fn(y_true, y_pred):
    return y_true

Let's create some tensors:

让我们创建一些张量:

from keras import backend as K

a = K.constant([1,2,3])
b = K.constant([4,5,6])

And use the keras.backend.eval()API to evaluate your loss function:

并使用keras.backend.eval()API 来评估您的损失函数:

loss = loss_fn(a,b)
K.eval(loss)
# array([1., 2., 3.], dtype=float32)

回答by Peter Svehla

I use

我用

print("y_true = " + str(y_true.eval()))

for debugging.

用于调试。

回答by H. M. Tarek Ullah

You can't get the values from the tensor symbolic variable directly. Yo need to write a theano function to extract the value. Don't forget to choose theano as backend of Keras.

您无法直接从张量符号变量中获取值。您需要编写一个 theano 函数来提取值。不要忘记选择 theano 作为 Keras 的后端。

Check the notebook link to get some basic of theano variables and functions : get tensor value in call function of own layers

检查笔记本链接以获取一些基本的 theano 变量和函数:在自己层的调用函数中获取张量值