【问题标题】:Evaluate a tensor in deferred mode in Tensorflow 2在 Tensorflow 2 中以延迟模式评估张量
【发布时间】:2019-11-20 16:08:29
【问题描述】:

我正在尝试评估张量的平方。 常数 = tf.constant([1, 2, 3]) tft = 常数*常数

#https://www.tensorflow.org/api_docs/python/tf/compat/v1/Session
sess = tf.compat.v1.Session()
with sess.as_default():
  print(tft.eval())

但是,它返回以下错误:

NotImplementedError: 急切执行时不支持 eval 启用,是 .numpy() 你在找什么?

我知道我可以禁用急切的 excuation

将张量流导入为 tf

tf.compat.v1.disable_eager_execution()
constant = tf.constant([1, 2, 3])
tft = constant*constant
print(tft)

但是,这会返回 Tensor("mul_4:0", shape=(3,), dtype=int32) 而不是实际值。请问如何评价?

任何帮助将不胜感激。

【问题讨论】:

    标签: session tensorflow2.0


    【解决方案1】:

    在 TF 2.x 中,您可以在会话中评估张量,如下所示

    import tensorflow as tf
    print(tf.__version__)
    
    with tf.compat.v1.Session() as sess:
      constant = tf.constant([1, 2, 3])
      tft = constant*constant
      print(tft.eval())
    

    输出:

    2.2.0
    [1 4 9]
    

    还有另一种没有会话的方法,您可以通过将tensor 转换为numpy 来查看实际值

    import tensorflow as tf
    import numpy as np
    print(tf.__version__)
    
    def tensor_to_array(array_value):
        return array_value.numpy()
    
    constant = tf.constant([1, 2, 3])
    tft = constant*constant
    
    print(tft)
    print(tensor_to_array(tft))
    

    输出:

    2.2.0
    tf.Tensor([1 4 9], shape=(3,), dtype=int32)
    [1 4 9]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2021-05-17
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      相关资源
      最近更新 更多