如何打印 Keras 张量的值? [英] How can I print the values of Keras tensors?

查看:123
本文介绍了如何打印 Keras 张量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的尝试

def loss_fn(y_true, y_pred):
    print y_true

打印

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

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

Is there any Keras function to access y_true values?

推荐答案

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

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

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 文档:

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

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

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.

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

So, make sure to use the tensor afterwards.

这篇关于如何打印 Keras 张量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆