【问题标题】:How to call the universal sentence encoder model in Python using tensorflow如何使用 tensorflow 在 Python 中调用通用句子编码器模型
【发布时间】:2020-05-06 19:53:32
【问题描述】:

我正在尝试使用通用句子编码模型来查找句子相似性。我在本地驱动器上保存了通用句子编码器模型形式。但是我不知道如何通过代码直接从下面的本地驱动器调用它,而不是通过代码中的链接调用它。请注意,我的操作系统是 Windows。

import tensorflow as tf
import tensorflow_hub as hub
embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder-large/3")
def get_features(texts):
    if type(texts) is str:
        texts = [texts]
    with tf.Session() as sess:
        sess.run([tf.global_variables_initializer(), tf.tables_initializer()])
        return sess.run(embed(texts))
get_features("The quick brown fox jumps over the lazy dog.I am a sentence for which I would like to get its embedding")

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    您可以使用hub.load 加载保存到驱动器的通用句子编码器模型。

    例如,USE-5 模型保存在名为5 的文件夹中,其文件夹结构如下图所示,我们可以使用下面提到的代码加载Model

    import tensorflow_hub as hub
    
    embed = hub.load('5')
    
    embeddings = embed([
        "The quick brown fox jumps over the lazy dog.",
        "I am a sentence for which I would like to get its embedding"])
    
    print(embeddings)
    

    以上代码的输出是:

    tf.Tensor([[ 0.01305105 0.02235123 -0.03263275 ... -0.00565093 -0.04793027 -0.11492756] [ 0.05833394 -0.08185011 0.06890941 ... -0.00923879 -0.08695354 -0.0141574 ]], shape=(2, 512), dtype=float32)
    

    上面的代码相当于下面的代码,它使用 URL 来加载 USE-5。

    import tensorflow_hub as hub
    
    embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder-large/5")
    
    embeddings = embed([ 
    "The quick brown fox jumps over the lazy dog.", 
    "I am a sentence for which I would like to get its embedding"])
    
    print(embeddings)
    

    【讨论】:

    • 非常感谢你帮助我@Tensorflow Warriors
    猜你喜欢
    • 2020-04-15
    • 2020-03-03
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多