【问题标题】:Convert a tensor to numpy array in Tensorflow?在 Tensorflow 中将张量转换为 numpy 数组?
【发布时间】:2016-03-09 21:55:41
【问题描述】:

在使用带有 Python 绑定的 Tensorflow 时如何将张量转换为 numpy 数组?

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    要将张量转换回 numpy 数组,您只需在转换后的张量上运行 .eval()

    【讨论】:

    • 澄清:yourtensor.eval()
    • 我收到 ValueError: Cannot evaluate tensor using 'eval()': No default session is registered. Use 'with sess.as_default()' or pass an explicit session to 'eval(session=sess)' 这是否仅在 tensoflow 会话期间可用?
    • @EduardoPignatelli 它在 Theano 中为我工作,无需额外工作。不确定 tf。
    • @EduardoPignatelli 您需要从会话内部运行.eval() 方法调用:sess = tf.Session(); with sess.as_default(): print(my_tensor.eval())
    • 通过使用这个我得到错误,因为 AttributeError: 'Tensor' object has no attribute 'eval'
    【解决方案2】:

    你需要:

    1. 将图像张量以某种格式(jpeg、png)编码为二进制张量
    2. 在会话中评估(运行)二进制张量
    3. 将二进制文件转成流
    4. 馈送到 PIL 图像
    5. (可选)使用 matplotlib 显示图像

    代码:

    import tensorflow as tf
    import matplotlib.pyplot as plt
    import PIL
    
    ...
    
    image_tensor = <your decoded image tensor>
    jpeg_bin_tensor = tf.image.encode_jpeg(image_tensor)
    
    with tf.Session() as sess:
        # display encoded back to image data
        jpeg_bin = sess.run(jpeg_bin_tensor)
        jpeg_str = StringIO.StringIO(jpeg_bin)
        jpeg_image = PIL.Image.open(jpeg_str)
        plt.imshow(jpeg_image)
    

    这对我有用。您可以在 ipython 笔记本中尝试。只是不要忘记添加以下行:

    %matplotlib inline
    

    【讨论】:

      【解决方案3】:

      Session.runeval 返回的任何张量都是 NumPy 数组。

      >>> print(type(tf.Session().run(tf.constant([1,2,3]))))
      <class 'numpy.ndarray'>
      

      或者:

      >>> sess = tf.InteractiveSession()
      >>> print(type(tf.constant([1,2,3]).eval()))
      <class 'numpy.ndarray'>
      

      或者,等效地:

      >>> sess = tf.Session()
      >>> with sess.as_default():
      >>>    print(type(tf.constant([1,2,3]).eval()))
      <class 'numpy.ndarray'>
      

      编辑:不是任何Session.runeval() 返回的张量是一个NumPy 数组。例如,稀疏张量作为 SparseTensorValue 返回:

      >>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
      <class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>
      

      【讨论】:

      • AttributeError: 模块 'tensorflow' 没有属性 'Session'
      • 如果单独使用 eval 就足够了,那么在所有这些选项中使用 Session.run 或 InteractiveSession 的原因是什么?
      • @Ceph 如果您在没有会话的情况下运行,则会收到以下错误:ValueError: Cannot evaluate tensor using 'eval()': No default session is registered. Use 'with sess.as_default()' or pass an explicit session to 'eval(session=sess)'
      【解决方案4】:

      也许你可以试试,这个方法:

      import tensorflow as tf
      W1 = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
      init = tf.global_variables_initializer()
      sess = tf.Session()
      sess.run(init)
      array = W1.eval(sess)
      print (array)
      

      【讨论】:

        【解决方案5】:

        我已经面对并解决了 tensor->ndarray 转换在张量表示(对抗性)图像的特定情况下,通过 cleverhans 库/教程获得。

        我认为我的问题/答案 (here) 对于其他情况也可能是一个有用的示例。

        我是 TensorFlow 新手,我的结论是经验性的:

        似乎 tensor.eval() 方法可能需要输入 placeholders 的值才能成功。 张量可能像函数一样工作,需要其输入值(提供给feed_dict)才能返回输出值,例如

        array_out = tensor.eval(session=sess, feed_dict={x: x_input})
        

        请注意,在我的例子中,占位符名称是 x,但我想您应该找出输入 placeholder 的正确名称。 x_input 是一个标量值或包含输入数据的数组。

        就我而言,还必须提供sess

        我的示例还涵盖了 matplotlib 图像可视化部分,但这是 OT。

        【讨论】:

          【解决方案6】:

          一个简单的例子可以是,

              import tensorflow as tf
              import numpy as np
              a=tf.random_normal([2,3],0.0,1.0,dtype=tf.float32)  #sampling from a std normal
              print(type(a))
              #<class 'tensorflow.python.framework.ops.Tensor'>
              tf.InteractiveSession()  # run an interactive session in Tf.
          

          n 现在如果我们想要这个张量 a 被转换成一个 numpy 数组

              a_np=a.eval()
              print(type(a_np))
              #<class 'numpy.ndarray'>
          

          就这么简单!

          【讨论】:

          • // 不适用于在 python 中进行评论。请编辑您的答案。
          【解决方案7】:

          TensorFlow 2.x

          Eager Execution 默认启用,因此只需在 Tensor 对象上调用 .numpy()

          import tensorflow as tf
          
          a = tf.constant([[1, 2], [3, 4]])                 
          b = tf.add(a, 1)
          
          a.numpy()
          # array([[1, 2],
          #        [3, 4]], dtype=int32)
          
          b.numpy()
          # array([[2, 3],
          #        [4, 5]], dtype=int32)
          
          tf.multiply(a, b).numpy()
          # array([[ 2,  6],
          #        [12, 20]], dtype=int32)
          

          请参阅NumPy Compatibility 了解更多信息。值得注意的是(来自文档),

          Numpy 数组可以与 Tensor 对象共享内存。 对其中一项的任何更改都可能反映在另一项中。

          我的大胆强调。可能会或可能不会返回副本,这是基于数据是在 CPU 中还是在 GPU 中的实现细节(在后一种情况下,必须从 GPU 复制到主机内存)。

          但为什么我会收到AttributeError: 'Tensor' object has no attribute 'numpy'
          很多人对这个问题发表了评论,有几个可能的原因:

          • TF 2.0 未正确安装(在这种情况下,请尝试重新安装),或者
          • TF 2.0 已安装,但由于某种原因禁用了急切执行。在这种情况下,请致电tf.compat.v1.enable_eager_execution() 启用它,或参见下文。

          如果 Eager Execution 被禁用,您可以构建一个图表,然后通过tf.compat.v1.Session 运行它:

          a = tf.constant([[1, 2], [3, 4]])                 
          b = tf.add(a, 1)
          out = tf.multiply(a, b)
          
          out.eval(session=tf.compat.v1.Session())    
          # array([[ 2,  6],
          #        [12, 20]], dtype=int32)

          另请参阅TF 2.0 Symbols Map,了解旧 API 到新 API 的映射。

          【讨论】:

          • 如何在 tf.function 中执行此操作?
          • 我在 TF 2.0 中收到以下错误:“'Tensor' object has no attribute 'numpy'”
          • 不,我没有禁用急切执行。仍然得到 AttributeError: 'Tensor' object has no attribute 'numpy'
          • 为什么会出现 AttributeError: 'Tensor' object has no attribute 'numpy'
          • 我使用的张量除了它的值之外还有一个梯度。我用mytensor.detach().numpy()
          【解决方案8】:

          我一直在寻找这个命令的日子。

          这对我来说在任何会话或类似的事情之外都有效。

          # you get an array = your tensor.eval(session=tf.compat.v1.Session())
          an_array = a_tensor.eval(session=tf.compat.v1.Session())
          

          https://kite.com/python/answers/how-to-convert-a-tensorflow-tensor-to-a-numpy-array-in-python

          【讨论】:

            【解决方案9】:

            你可以使用keras后端功能。

            import tensorflow as tf
            from tensorflow.python.keras import backend 
            
            sess = backend.get_session()
            array = sess.run(< Tensor >)
            
            print(type(array))
            
            <class 'numpy.ndarray'>
            

            希望对你有帮助!

            【讨论】:

              【解决方案10】:

              如果你看到有一个方法_numpy(), 例如,对于 EagerTensor,只需调用上述方法,您就会得到一个 ndarray。

              【讨论】:

                【解决方案11】:

                您可以通过以下方式将tensorflow 中的张量转换为numpy 数组。

                第一: 使用np.array(your_tensor)

                第二: 使用your_tensor.numpy

                【讨论】:

                • np.array(your_tensor) 不起作用。 NotImplementedError:无法将符号张量 (truediv:0) 转换为 numpy 数组。此错误可能表明您正在尝试将张量传递给 NumPy 调用,这是不受支持的
                【解决方案12】:

                关于 TensorFlow 2.x

                以下通常有效,因为默认情况下激活了急切执行:

                import tensorflow as tf
                
                a = tf.constant([[1, 2], [3, 4]])                 
                b = tf.add(a, 1)
                
                print(a.numpy())
                # [[1 2]
                #  [3 4]]
                

                但是,由于很多人似乎都在发布错误:

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

                我认为公平地说,在图形模式下调用 tensor.numpy()起作用。这是一个简单的例子:

                import tensorflow as tf
                
                @tf.function
                def add():
                  a = tf.constant([[1, 2], [3, 4]])                 
                  b = tf.add(a, 1)
                  tf.print(a.numpy()) # throws an error!
                  return a
                add()
                

                简单的解释可以找here:

                从根本上说,不能将图张量转换为 numpy 数组,因为该图不在 Python 中执行 - 因此在图执行时没有 NumPy。 [...]

                TFdocs也值得一看。

                关于使用 Tensorflow 2.x 的 Keras 模型

                这也适用于Keras 模型,默认情况下它们被包裹在tf.function 中。如果确实需要运行tensor.numpy(),可以在model.compile(*)中设置参数run_eagerly=True,但这会影响模型的性能。

                【讨论】:

                  猜你喜欢
                  • 2020-12-31
                  • 1970-01-01
                  • 2021-10-13
                  • 2021-04-28
                  • 2021-10-17
                  • 2018-11-28
                  • 1970-01-01
                  • 2016-10-15
                  • 2020-01-23
                  相关资源
                  最近更新 更多