简体   繁体   English

如何在 Tensorflow 2.1.0 中将张量转换为 Eager 张量?

[英]How to convert a Tensor to Eager tensor in Tensorflow 2.1.0?

I've been trying to convert a tensor of type:我一直在尝试转换类型的张量:

tensorflow.python.framework.ops.Tensor

to an eagertensor:对一个热心的人:

<class 'tensorflow.python.framework.ops.EagerTensor'>

I've been searching for a solution but couldn't find one.我一直在寻找解决方案,但找不到。 Any help would be appreciated.任何帮助,将不胜感激。

Context:语境:

I have obtained the tensor using the feature extraction method from a Keras Sequential model.我已经使用 Keras Sequential 模型的特征提取方法获得了张量。 The output was a tensor of the first mentioned type.输出是第一个提到的类型的张量。 However, when I tried to convert it to numpy using .numpy(), it did not work with the following error:但是,当我尝试使用 .numpy() 将其转换为 numpy 时,它并没有出现以下错误:

'Tensor' object has no attribute 'numpy'

But then when I try creating a tensor using tf.constant and then using .numpy() to convert it, it works fine!但是当我尝试使用 tf.constant 创建张量然后使用 .numpy() 来转换它时,它工作正常!

The only difference I found is that the types of tensors are different: The tensor generated by Keras sequential is of the first type mentionned above, whereas the second tensor that I have created manually is of the second type (Eager tensor).我发现唯一的区别是张量的类型不同:Keras序列生成的张量是上面提到的第一种类型,而我手动创建的第二种张量是第二种类型(Eager tensor)。

Could have answered better if you would have shared the reproducible code.如果您可以共享可重现的代码,本可以更好地回答。

Below is a simple scenario where I have recreated your error.下面是一个简单的场景,我在其中重新创建了您的错误。 Here I am reading the path of a image file.在这里,我正在读取图像文件的路径。

Code to recreate the error:重新创建错误的代码:

%tensorflow_version 2.x
import tensorflow as tf
import numpy as np

def get_path(file_path):
    print("file_path: ", bytes.decode(file_path.numpy()),type(bytes.decode(file_path.numpy())))
    return file_path

train_dataset = tf.data.Dataset.list_files('/content/bird.png')
train_dataset = train_dataset.map(lambda x: (get_path(x)))

for one_element in train_dataset:
    print(one_element)

Output:输出:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-2d5db8425f67> in <module>()
      8 
      9 train_dataset = tf.data.Dataset.list_files('/content/bird.png')
---> 10 train_dataset = train_dataset.map(lambda x: (get_path(x)))
     11 
     12 for one_element in train_dataset:

10 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/autograph/impl/api.py in wrapper(*args, **kwargs)
    256       except Exception as e:  # pylint:disable=broad-except
    257         if hasattr(e, 'ag_error_metadata'):
--> 258           raise e.ag_error_metadata.to_exception(e)
    259         else:
    260           raise

AttributeError: in user code:

    <ipython-input-8-2d5db8425f67>:10 None  *
        train_dataset = train_dataset.map(lambda x: (get_path(x)))
    <ipython-input-8-2d5db8425f67>:6 get_path  *
        print("file_path: ", bytes.decode(file_path.numpy()),type(bytes.decode(file_path.numpy())))

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

Below are the steps I have implemented in the code to fix this error.以下是我在代码中为修复此错误而实施的步骤。

  1. Have decorated the map function with tf.py_function(get_path, [x], [tf.string]) .tf.py_function(get_path, [x], [tf.string])修饰了 map 函数。 You can find more about tf.py_function here .您可以在此处找到有关 tf.py_function 的更多信息。
  2. Now I can get the string part by using bytes.decode(file_path.numpy()) in map function.现在我可以通过在 map 函数中使用bytes.decode(file_path.numpy())来获取字符串部分。

Fixed Code:固定代码:

%tensorflow_version 2.x
import tensorflow as tf
import numpy as np

def get_path(file_path):
    print("file_path: ",bytes.decode(file_path.numpy()),type(bytes.decode(file_path.numpy())))
    return file_path

train_dataset = tf.data.Dataset.list_files('/content/bird.jpg')
train_dataset = train_dataset.map(lambda x: tf.py_function(get_path, [x], [tf.string]))

for one_element in train_dataset:
    print(one_element)

Output:输出:

file_path:  /content/bird.jpg <class 'str'>
(<tf.Tensor: shape=(), dtype=string, numpy=b'/content/bird.jpg'>,)

Hope this answers your question.希望这能回答你的问题。

Writing one more answer as the same error appears on different scenario.由于相同的错误出现在不同的场景中,所以再写一个答案。

The error you are getting is because of version issue .ie tensorflow version 2.1.0 .你得到的错误是因为版本问题 .ie tensorflow version 2.1.0 I ran the code by skipping the first 2 paragraphs that is to install tensorflow==2.1.0 and keras==2.3.1 and the error didn't reappear.我通过跳过安装tensorflow==2.1.0keras==2.3.1的前两段来运行代码,并且错误没有再次出现。

Your issue vanishes in the latest version of the tensorflow version 2.3.0 .您的问题在最新版本的tensorflow version 2.3.0消失了。 Run the program on latest versions, that means do not install tensorflow and keras again because Google Colab already has the latest and stable version pre installed.在最新版本上运行程序,这意味着不要再次安装 tensorflow 和 keras,因为 Google Colab 已经预先安装了最新且稳定的版本。

features.numpy()

Output -输出 -

array([[0.       , 0.3728346, 0.       , ..., 1.0103987, 0.       ,
        0.4194043]], dtype=float32)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM