【问题标题】:How to read elements of a tensor in Tensorflow?如何在 Tensorflow 中读取张量的元素?
【发布时间】:2021-11-05 07:49:37
【问题描述】:

我正在尝试在 tensorflow (V 2.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'

【问题讨论】:

  • 您是否有理由强制使用 tf 1 而不是使用 tf 2?

标签: python numpy tensorflow keras tensor


【解决方案1】:

在 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))

【讨论】:

    【解决方案2】:

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

    在 tensorflow v1 中,您无法从会话中访问张量。所以你不能打电话给a.numpy()

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

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

    【讨论】:

    • 它有效,但在我之前执行 tf.quantize 时无效。示例 t = tf.constant([[1.5,1.445,1.66], [1.255,1.44999,1.5111]]) 与 tf.compat.v1.Session() 作为 sess: print(q.eval())
    • 它返回:AttributeError:'QuantizeV2'对象没有属性'eval'。提前谢谢你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2020-03-19
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多