【发布时间】:2020-07-14 07:25:28
【问题描述】:
将 tensforflow 与烧瓶 REST API 结合使用
我应该如何减少session.run的时间
我在 REST API 中使用 tf 1/2,而不是在我的服务器上使用它。
我已经尝试过 tensorflow 1 和 2。
tensorflow 1 花费了太多时间。
tensorflow 2 甚至没有返回文本的向量。
在张量流 1 中
初始化需要 2-4 秒,session.run 需要 5-8 秒。
随着我不断满足要求,时间越来越长。
张量流 1
import tensorflow.compat.v1 as tfo
import tensorflow_hub as hub
tfo.disable_eager_execution()
module_url = "https://tfhub.dev/google/universal-sentence-encoder-qa/3"
# Import the Universal Sentence Encoder's TF Hub module
embed = hub.Module(module_url)
def convert_text_to_vector(text):
# Compute a representation for each message, showing various lengths supported.
try:
#text = "qwerty" or ["qwerty"]
if isinstance(text, str):
text = [text]
with tfo.Session() as session:
t_time = time.time()
session.run([tfo.global_variables_initializer(), tfo.tables_initializer()])
m_time = time.time()
message_embeddings = session.run(embed(text))
vector_array = message_embeddings.tolist()[0]
return vector_array
except Exception as err:
raise Exception(str(err))
张量流 2
卡在vector_array = embedding_fn(text)
import tensorflow as tf
import tensorflow_hub as hub
module_url = "https://tfhub.dev/google/universal-sentence-encoder-qa/3"
embedding_fn = hub.load(module_url)
@tf.function
def convert_text_to_vector(text):
try:
#text = ["qwerty"]
vector_array = embedding_fn(text)
return vector_array
except Exception as err:
raise Exception(str(err))
【问题讨论】:
-
嗨,对于 tensorflow 2 代码 sn-p,如果您使用 vector_array = embedding_fn.signatures['question_encoder'](tf.constant(text)) 会怎样。我测试了它,它对我有用。让我知道这是否是您的预期用途。最佳
-
@smile 我正在使用烧瓶,但它无法在其中工作。但是我发布的两个示例和您提供的解决方案都可以在 Jupyter Notebook 中正常工作。
-
嗨,您可以展示如何从烧瓶中获取参数。或者也许首先在烧瓶外运行它以获得更好的调试。这样您就可以轻松地将烧瓶问题与 tensorflow 分开。最佳
-
调用顺序:app.py -> controllers.py -> vectorisation.py。控制器调用 convert_text_to_vector(在 vectorisation.py 中)。调用 convert_text_to_vector 时的参数是 text = ['qwerty']
-
嗨,我应该发布一个简单的工作示例吗?可能有用吗?最佳
标签: python tensorflow tensorflow2.0 sentence-similarity