如何使用张量流服务使张量流集线器嵌入可服务?

2024-04-03

我正在尝试使用来自tensorflow hub的嵌入模块作为可服务。我是张量流新手。目前,我正在使用通用句子编码器 https://tfhub.dev/google/universal-sentence-encoder/1嵌入作为将句子转换为嵌入的查找,然后使用这些嵌入来查找与另一个句子的相似性。

我当前将句子转换为嵌入的代码是:

with tf.Session() as session:
  session.run([tf.global_variables_initializer(), tf.tables_initializer()])
  sen_embeddings = session.run(self.embed(prepared_text))

Prepared_text 是句子列表。我如何采用这个模型并使其成为可用的?


现在您可能需要手动执行此操作。这是我的解决方案,与之前的答案类似,但更通用 - 展示如何在不猜测输入参数的情况下使用任何其他模块,以及如何通过验证和使用进行扩展:

import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.saved_model import simple_save

export_dir = "/tmp/tfserving/universal_encoder/00000001"
with tf.Session(graph=tf.Graph()) as sess:
    module = hub.Module("https://tfhub.dev/google/universal-sentence-encoder/2") 
    input_params = module.get_input_info_dict()
    # take a look at what tensor does the model accepts - 'text' is input tensor name

    text_input = tf.placeholder(name='text', dtype=input_params['text'].dtype, 
        shape=input_params['text'].get_shape())
    sess.run([tf.global_variables_initializer(), tf.tables_initializer()])

    embeddings = module(text_input)

    simple_save(sess,
        export_dir,
        inputs={'text': text_input},
        outputs={'embeddings': embeddings},
        legacy_init_op=tf.tables_initializer())

谢谢module.get_input_info_dict()您知道需要传递给模型的张量名称 - 您使用该名称作为关键inputs={} in simple_save method.

请记住,要为模型提供服务,它需要位于以版本结尾的目录路径中,这就是为什么'00000001'是最后一条路径saved_model.pb居住。

导出模块后,查看模型是否正确导出以供服务的最快方法是使用已保存_model_cli API https://www.tensorflow.org/guide/saved_model#cli_to_inspect_and_execute_savedmodel:

saved_model_cli run --dir /tmp/tfserving/universal_encoder/00000001 --tag_set serve --signature_def serving_default --input_exprs 'text=["what this is"]'

要从 docker 提供模型:

docker pull tensorflow/serving  
docker run -p 8501:8501 -v /tmp/tfserving/universal_encoder:/models/universal_encoder -e MODEL_NAME=universal_encoder -t tensorflow/serving                                                                                           
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用张量流服务使张量流集线器嵌入可服务? 的相关文章

随机推荐