在TF 2.x中将Tensor转换为numpy数组

问题描述

我正在尝试加载Universal Sentence Encoder,这是我的代码段:

import tensorflow as tf
import tensorflow_hub as hub
import os,requests,tarfile

def extractUSEEmbeddings(words):
    # Extracts USE embeddings
    # Replace `USE_folder` with any directory in your machine,where you want USE to be downloaded
    try:
        embed = hub.KerasLayer(USE_folder)
    except Exception as e:
        print ("Downloading USE embeddings...")
        r = requests.get("https://tfhub.dev/google/universal-sentence-encoder-large/5?tf-hub-format=compressed")
        open("USE.tar.gz","wb").write(r.content)
        
        tar = tarfile.open("USE.tar.gz","r:gz")
        tar.extractall(path=USE_folder)
        tar.close()

        os.remove("USE.tar.gz")
        embed = hub.KerasLayer(USE_folder)
        pass
    word_embeddings = embed(words)
    return word_embeddings.numpy()

我收到错误'Tensor' object has no attribute 'numpy'。当我在Jupyter笔记本上运行相同的代码,并使用相同版本的tensorflow(2.2.0)和tensorflow-hub(0.9.0)时,我没有收到任何错误,并且可以正常工作。 / p>

我在两种情况下都打印了Tensor的type,并且意识到这是因为我在Jupyter中得到了Eager Tensor方法tensorflow.python.framework.ops.EagerTensornumpy)而在我的脚本中,Tensor的类型为tensorflow.python.framework.ops.Tensor。但是,现在我无法弄清楚如何在脚本中打开Eager Execution,因为在TF 2.x中应该认启用它。

我已经尝试了this thread中提供的所有解决方案,但没有一个适合我。

为什么通过终端运行时我没有得到渴望的张量,而通过Jupyter获得它呢?我的问题与我在这里使用tensorflow-hub有关,这就是为什么没有一个解决方案对我有用吗?最重要的是,如何将tf 2.x中的Tensor转换为numpy数组?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...