问题描述
我正在尝试加载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.EagerTensor
(numpy
)而在我的脚本中,Tensor
的类型为tensorflow.python.framework.ops.Tensor
。但是,现在我无法弄清楚如何在脚本中打开Eager Execution,因为在TF 2.x中应该默认启用它。
我已经尝试了this thread中提供的所有解决方案,但没有一个适合我。
为什么通过终端运行时我没有得到渴望的张量,而通过Jupyter获得它呢?我的问题与我在这里使用tensorflow-hub
有关,这就是为什么没有一个解决方案对我有用吗?最重要的是,如何将tf 2.x中的Tensor
转换为numpy
数组?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)