Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何打印Keras张量的值?_Python_Neural Network_Keras_Tensor - Fatal编程技术网

Python 如何打印Keras张量的值?

Python 如何打印Keras张量的值?,python,neural-network,keras,tensor,Python,Neural Network,Keras,Tensor,我正在实现自己的Keras损失函数。如何访问张量值 我试过的 def loss_fn(y_true, y_pred): print y_true 它打印 Tensor("target:0", shape=(?, ?), dtype=float32) 是否有任何Keras功能来访问y\u true值?通常,在准备列车资料时,y\u true 但是,有一个技巧可以查看y\u true和/或y\u pred中的值。Keras为您提供了一个编写用于打印神经网络输出的相应文件的机会。 它看起来

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

我试过的

def loss_fn(y_true, y_pred):
    print y_true
它打印

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

是否有任何Keras功能来访问
y\u true
值?

通常,在准备列车资料时,
y\u true

但是,有一个技巧可以查看
y\u true
和/或
y\u 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]
aa = tf.constant([[1,5,3]])
bb = keras.layers.Dense(4, name="my_tensor")
print('bb.weights before a assign:',bb.weights,'\n')
print('bb:',bb(aa),'\n')                               
print('bb.weights:',bb.weights)
在这里,
loss\u fn
是在编译模型时将loss函数传递到
model.compile(…,metrics=[loss\u fn],)
函数的名称

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

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


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

不能直接从张量符号变量中获取值。你需要写一个theano函数来提取这个值。别忘了选择theano作为Keras的后端


检查笔记本链接以获取一些基本的无变量和函数:

Keras'后端具有
打印张量
,您可以使用它来执行此操作。您可以这样使用它:

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 = ')
    ...
该函数返回一个相同的张量。当计算该张量时,它将打印其内容,前面是
消息
。 从:

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


因此,请确保在之后使用tensor。

如果使用TensorFlow的keras,可以启用:

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

如果您收到错误消息“ValueError:在急切模式下仅支持TF本机优化器”,并且您使用了“adam”作为优化器,您可以将模型的编译参数更改为

model.compile(optimizer = tf.train.AdamOptimizer(), loss = loss_fn, ...)
更新:TensorFlow 2.x

您只需启用“急切运行”参数即可急切执行Keras模型,如中所述:

之后,您可以使用
print(y\u-true)
tf.print(y\u-true)
K.print\u-tensor(y\u-true)
I使用

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

用于调试。

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

def丢失fn(y_真,y_pred):
返回y_true
让我们创建一些张量:

从keras导入后端为K
a=K.常数([1,2,3])
b=K.常数([4,5,6])
并使用API评估损失函数:

loss=loss\u fn(a,b)
K.评估(损失)
#数组([1,2,3.],dtype=float32)

要打印张量的值,需要张量具有值 例如:

import tensorflow as tf

aa = tf.constant([1,5,3])
bb = keras.layers.Dense(4, name="my_tensor")
print('aa:',aa)
print('bb:',bb)


aa: tf.Tensor([1 5 3], shape=(3,), dtype=int32)
bb: <tensorflow.python.keras.layers.core.Dense object at 0x000001D4B0137048>
输出:

bb.weight before a assign: [] 

bb: tf.Tensor([[1.0374807 3.4536252 1.5064619 2.1762671]], shape=(1, 4), dtype=float32) 

bb.weight: [<tf.Variable 'my_tensor/kernel:0' shape=(3, 4) dtype=float32, numpy=
array([[ 0.885918  , -0.88332534, -0.40944284, -0.04479438],
       [-0.27336687,  0.34549594, -0.11853147,  0.15316617],
       [ 0.50613236,  0.8698236 ,  0.83618736,  0.4850769 ]],
      dtype=float32)>, <tf.Variable 'my_tensor/bias:0' shape=(4,) dtype=float32, numpy=array([0., 0., 0., 0.], dtype=float32)>]
TypeError: 'tensorflow.python.framework.ops.EagerTensor' object is not callable
feature_extractor: tf.Tensor([[-4.9181094  4.956725  -1.8055304  2.6975303]], shape=(1, 4), dtype=float32) 



输出:

bb.weight before a assign: [] 

bb: tf.Tensor([[1.0374807 3.4536252 1.5064619 2.1762671]], shape=(1, 4), dtype=float32) 

bb.weight: [<tf.Variable 'my_tensor/kernel:0' shape=(3, 4) dtype=float32, numpy=
array([[ 0.885918  , -0.88332534, -0.40944284, -0.04479438],
       [-0.27336687,  0.34549594, -0.11853147,  0.15316617],
       [ 0.50613236,  0.8698236 ,  0.83618736,  0.4850769 ]],
      dtype=float32)>, <tf.Variable 'my_tensor/bias:0' shape=(4,) dtype=float32, numpy=array([0., 0., 0., 0.], dtype=float32)>]
TypeError: 'tensorflow.python.framework.ops.EagerTensor' object is not callable
feature_extractor: tf.Tensor([[-4.9181094  4.956725  -1.8055304  2.6975303]], shape=(1, 4), dtype=float32) 



我使用功能提取程序修复它:

inputs = keras.Input(shape=(3,), name="inputs")
bb = keras.layers.Dense(4, name="my_tensor")(inputs)

feature_extractor = keras.Model(
    inputs=inputs,
    outputs=bb,
)

aa = tf.constant([[1,5,3]])
print('feature_extractor:',feature_extractor(aa),'\n')
输出:

bb.weight before a assign: [] 

bb: tf.Tensor([[1.0374807 3.4536252 1.5064619 2.1762671]], shape=(1, 4), dtype=float32) 

bb.weight: [<tf.Variable 'my_tensor/kernel:0' shape=(3, 4) dtype=float32, numpy=
array([[ 0.885918  , -0.88332534, -0.40944284, -0.04479438],
       [-0.27336687,  0.34549594, -0.11853147,  0.15316617],
       [ 0.50613236,  0.8698236 ,  0.83618736,  0.4850769 ]],
      dtype=float32)>, <tf.Variable 'my_tensor/bias:0' shape=(4,) dtype=float32, numpy=array([0., 0., 0., 0.], dtype=float32)>]
TypeError: 'tensorflow.python.framework.ops.EagerTensor' object is not callable
feature_extractor: tf.Tensor([[-4.9181094  4.956725  -1.8055304  2.6975303]], shape=(1, 4), dtype=float32) 




要获得任意层keras张量的输出值(“如何打印keras张量的值?”),似乎需要不同的解决方案。要打印单个图层的输出(从):


如何打印其值?我做了那件事,什么也没说出来。使用Tensorflow后端。这看起来不错,但较长的张量并不是完整打印的(例如:softmax=[[0.0599291697 0.0380649045 0.0828271]…])。你知道完整打印它们(或者至少控制打印多长时间)的方法吗?@Pablo我找不到任何关于此功能的参考。使用tensorflow后端,实现uses,它接收可提供此功能的
summary
参数,但Keras'
print\u tensor
不转发该参数。您可以尝试手动将
summary
参数添加到
print\u tensor
中。是的,这可能是唯一的方法()这对我不起作用。丢失函数中没有
print()
tf.print()
K.print\u tensor
worked@Rylan:我已经更新了TensorFlow 2的答案。希望它对你有用!