如何在Tensorflow中读取张量的元素?



我试图在tensorflow (v2.6.0)中读取张量的元素。为此,我尝试了许多方法,但没有一种对我有效。

假设我们想访问a的元素。

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
a = tf.constant([[1,2,3],[4,5,6]]) 

第一次尝试

a.numpy() 

返回错误:

AttributeError: 'Tensor' object has no attribute 'numpy'

之后我又试了:

np.array(a) 

误差

NotImplementedError: Cannot convert a symbolic Tensor (Reshape_5:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported

去年:

from tensorflow.python.keras.backend import get_session
a.eval(session=K.get_session())

AttributeError: module 'keras.api._v2.keras.backend' has no attribute 'get_session'

在Tensorflow 2+中有两种读取张量元素的方法。

  1. 删除tf.disable_v2_behavior()
import tensorflow.compat.v1 as tf
a = tf.constant([[1, 2, 3], [4, 5, 6]])
print(a.numpy())
  1. 使用会话
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
a = tf.constant([[1, 2, 3], [4, 5, 6]])
with tf.Session() as sess:
print(sess.run(a))

您正在禁用tensorflow 2与tf.disable_v2_behavior()

在tensorflow v1中,你不能在会话之外访问张量。因此不能调用a.numpy()

我建议你要么启用v2,要么计算v1中的张量,你必须进入一个会话:

with tf.compat.v1.Session() as sess:
print(a.eval())
# Output:
# [[1 2 3]
#  [4 5 6]]

最新更新