简体   繁体   English

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

[英]How to print value of tensorflow.python.framework.ops.Tensor in Tensorflow 2.0?

I have a few tensors in my code and and need to get the values of those tensors.我的代码中有几个张量,需要获取这些张量的值。 This is one them.这是他们中的一个。 How to print the values of tensor OA?如何打印张量 OA 的值?

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

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

I have tried all the available functions like tf.print(), eval(), tensor.numpy().我已经尝试了所有可用的函数,如 tf.print()、eval()、tensor.numpy()。 None of them worked for me in Tensorflow 2.0.他们都没有在 Tensorflow 2.0 中为我工作。 It seems they work only for 'EagerTensor' and not for 'ops.Tensor'.它们似乎只适用于“EagerTensor”而不适用于“ops.Tensor”。

1) OA.eval(session=sess) Error: ValueError: Cannot use the given session to evaluate tensor: the tensor's graph is different from the session's graph. 1) OA.eval(session=sess) 错误:ValueError:无法使用给定的 session 评估张量:张量的图形与会话的图形不同。

2) tf.print(OA) Output: 2) tf.print(OA) Output:

3) print (OA.numpy()) Output: AttributeError: 'Tensor' object has no attribute 'numpy' 3) print (OA.numpy()) Output: AttributeError: 'Tensor' object 没有属性 'numpy'

Is there any way to convert ops.Tensor to EagerTensor to try the above functions?有什么方法可以将 ops.Tensor 转换为 EagerTensor 来尝试上述功能吗? Or is there any other option to print the values of ops.Tensor.或者是否有任何其他选项来打印 ops.Tensor 的值。 Please advise.请指教。

-- Adding the minimal code to reproduce the example ops.Tensor in TF2.0. --添加最少的代码以在 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)

Output: Tensor("bidirectional_3/concat:0", shape=(512, 600), dtype=float32) Output: 张量("bidirectional_3/concat:0", shape=(512, 600), dtype=float32)

type(HQ)类型(总部)

Output: tensorflow.python.framework.ops.Tensor Output: tensorflow.python.framework.ops.Tensor

How to check the actual values of this tensor?如何检查这个张量的实际值?

Your graph is not complete at the point you are printing HQ.在您打印 HQ 时,您的图表不完整。 You need to complete the model creation.您需要完成模型创建。 Presumably something like大概是这样的

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

The trick to print an intermediate layer is to just make it an output.打印中间层的技巧就是让它成为一个输出。 You can make it an additional output of your existing model temporarily, or just make a new model.您可以暂时将其作为现有模型的附加输出,或者只是制作一个新模型。

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

now run inference on your inspection_model to get the value of the intermediate activation HQ.现在对您的检查模型运行推理以获取中间激活 HQ 的值。

print(inspection_model(xyz))

Directly you cannot print the values of tensors the way you are trying to do.您不能直接按照您尝试的方式打印张量的值。 Tensorflow 2.x by default runs in eager mode and also you have given no input to your incomplete model. Tensorflow 2.x 默认以 eager 模式运行,而且您没有为不完整的 model 提供任何输入。

The way to do it is by using the custom training loop.方法是使用自定义训练循环。 Suppose the layers mentioned in your code stack up to create a model my_model .假设代码中提到的层堆叠起来创建一个 model my_model

from tensorflow.keras import Model


my_model = Model(input_text, outputs=HQ)

with tf.GradientTape() as t:
    HQ_predictions = my_model(input_data)
print(HQ_predictions)

使用.numpy()属性,如:

your_tensor.numpy()

my tensorflow version is 2.5.0,here is an example of showing values:我的 tensorflow 版本是 2.5.0,这是显示值的示例:

import tensorflow as tf

print(tf.__version__) # 2.5.0

num=1
print(type(tf.constant(num,dtype="int64"))) # <class 'tensorflow.python.framework.ops.EagerTensor'>
print(tf.constant(num,dtype="int64").numpy()) # 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Tensorflow Batchnormalization - 类型错误:轴必须是整数或列表,类型给定:<class 'tensorflow.python.framework.ops.Tensor'> - Tensorflow Batchnormalization - TypeError: axis must be int or list, type given: <class 'tensorflow.python.framework.ops.Tensor'> ValueError:特征应该是`Tensor`的字典。 给定类型: <class 'tensorflow.python.framework.ops.Tensor'> - ValueError: features should be a dictionary of `Tensor`s. Given type: <class 'tensorflow.python.framework.ops.Tensor'> Unable to convert tensorflow.python.framework.ops.Tensor object to numpy array for passoing it in sklearn.metrics.cohen_kappa_score function - Unable to convert tensorflow.python.framework.ops.Tensor object to numpy array for passoing it in sklearn.metrics.cohen_kappa_score function 张量的Tensorflow打印值 - Tensorflow print value of a tensor 在Tensorflow中打印张量的值 - Print the value of a tensor in Tensorflow 项目分配 Tensorflow 2.0 - TypeError: 'tensorflow.python.framework.ops.EagerTensor' object 不支持项目分配 - Item Assignment Tensorflow 2.0 - TypeError: 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment 检查 Tensorflow 2.0 中张量的值 - Inspect value of a tensor in Tensorflow 2.0 如何在 TensorFlow 中打印 Tensor 对象的值? - How to print the value of a Tensor object in TensorFlow? 在此示例中,如何打印tensorflow张量值? - How to print tensorflow tensor value in this example? AttributeError: &#39;tensorflow.python.framework.ops.EagerTensor&#39; 对象没有属性 &#39;to_tensor&#39; - AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'to_tensor'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM