如何在tensorflow 2.0中打印tensorflow.python.framework.ops.Tensor的值?

2024-04-26 15:01:01 发布

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

我的代码中有一些张量,需要得到这些张量的值。这是其中之一。如何打印张量OA的值

Input:OA
Output: <tf.Tensor 'Sum_1:0' shape=(1, 600) dtype=float32>

Input:type(OA)
Output: tensorflow.python.framework.ops.Tensor

我已经尝试了所有可用的函数,如tf.print()、eval()、tensor.numpy()。在Tensorflow 2.0中没有一个为我工作。似乎它们只适用于“张量”,而不适用于“运算张量”

1)OA.eval(会话=sess) 错误:ValueError:无法使用给定会话计算张量:张量图与会话图不同

2)tf.打印(OA) 输出:

3)打印(OA.numpy()) 输出:AttributeError:“Tensor”对象没有属性“numpy”

有没有办法把ops.Tensor转换成EquiredTensor来尝试上面的函数?或者是否有其他选项打印ops.Tensor的值。请告知

-->strong>添加最小代码以在TF2.0中重现示例ops.Tensor。

!pip install tensorflow==2.0.0
tf.__version__

import tensorflow as tf
from keras.layers import Dense, Conv1D, MaxPooling1D, Flatten, Dropout, Input, Embedding, Bidirectional, LSTM
from tensorflow.keras import regularizers

EMBEDDING_DIM = 300
max_length = 120
batch_size = 512
vocab_size = 1000
units = 300

from keras.layers import Dense, Conv1D, MaxPooling1D, Flatten, Dropout, Input, Embedding, Bidirectional, LSTM
from tensorflow.keras import regularizers

input_text = tf.keras.Input(shape= (max_length), batch_size=batch_size)

embedding_layer = tf.keras.layers.Embedding(vocab_size, EMBEDDING_DIM, input_length =max_length, name="Embedding_Layer_1")
embedding_sequence = embedding_layer(input_text)

HQ = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(units,recurrent_dropout=0.5,kernel_regularizer=regularizers.l2(0.001),return_sequences=True,name='Bidirectional_1'))(embedding_sequence)
HQ = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(units,recurrent_dropout=0.5,kernel_regularizer=regularizers.l2(0.001),name='Bidirectional_2'))(HQ)

print (HQ)

输出:张量(“双向_3/concat:0”,shape=(512600),dtype=float32)

类型(HQ)

输出:tensorflow.python.framework.ops.Tensor

如何检查这个张量的实际值


Tags: fromimportinputsizelayerstftensorflowembedding
2条回答

使用.numpy()属性,如:

your_tensor.numpy()

在打印HQ时,图形不完整。您需要完成模型创建。大概是

output = tf.keras.layers.xyz()(HQ)
model = tf.keras.models.Model(input_text, output)

打印中间层的诀窍是将其作为输出。您可以临时将其作为现有模型的附加输出,也可以仅创建一个新模型

inspection_model = tf.keras.models.Model(input_text, [output, HQ])

现在在您的检查模型上运行推断,以获得中间激活HQ的值

print(inspection_model(xyz))

相关问题 更多 >