【问题标题】:tensorflow 1 Session.run is taking too much time to embed sentence using universal sentence encodertensorflow 1 Session.run 使用通用句子编码器嵌入句子花费了太多时间
【发布时间】: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


【解决方案1】:

对于 tensorflow 2 版本,我做了一些更正。基本上我遵循了您提供的universal sentence encoder 中的示例。

import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
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:
      vector_array = embedding_fn.signatures['question_encoder'](
          tf.constant(text))
      return vector_array['outputs']
  except Exception as err:
      raise Exception(str(err))

### run the function
vector = convert_text_to_vector(['is this helpful ?'])
print(vector.shape())

【讨论】:

  • 在 jupyter notebook 中工作正常,但在烧瓶中却不行。
  • 嗨,可以为在烧瓶上的部署提供一个最小的工作示例吗?最佳
【解决方案2】:
from flask import Flask
from flask_restplus import Api, Resource
from werkzeug.utils import cached_property

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)


app = Flask(__name__)

@app.route('/embedding', methods=['POST'])
def entry_point(args):
    if args.get("text"):
        text_term = args.get("text")
        if isinstance(text_term, str):
            text_term = [text_term]
        vectors = convert_text_to_vector(text_term)
    return vectors



@tf.function
def convert_text_to_vector(text):
    try:
        vector_array = embedding_fn.signatures['question_encoder'](tf.constant(text))
        return vector_array['outputs']
    except Exception as err:
        raise Exception(str(err))


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

"""
 ----- Requirements.txt ----
flask-restplus==0.13.0
Flask==1.1.1
Werkzeug==0.15.5
tensorboard==2.2.2
tensorboard-plugin-wit==1.6.0.post3
tensorflow==2.2.0
tensorflow-estimator==2.2.0
tensorflow-hub==0.8.0
tensorflow-text==2.2.1
"""

【讨论】:

  • @smile 烧瓶应用
猜你喜欢
  • 2018-09-12
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 2014-01-13
  • 2021-03-13
  • 2021-04-26
  • 1970-01-01
相关资源
最近更新 更多