如何将 tensorflow-hub 模块与 tensorflow-dataset 一起使用 api

How to use tensorflow-hub module with tensorflow-dataset api

我想使用 Tensorflow 数据集 api 通过 tensorflow Hub 初始化我的数据集。我想使用 dataset.map 函数将我的文本数据转换为嵌入。我的 Tensorflow 版本是 1.14.

因为我使用了 elmo v2 modlule 将一堆句子数组转换成它们的词嵌入,所以我使用了以下代码:

import tensorflow as tf
import tensorflow_hub as hub
...
sentences_array = load_sentences()
#Sentence_array=["I love Python", "python is a good PL"]
def parse(sentences):
    elmo = hub.Module("./ELMO")
    embeddings = elmo([sentences], signature="default", as_dict=True) 
    ["word_emb"]
    return embeddings
dataset = tf.data.TextLineDataset(sentences_array)
dataset = dataset.apply(tf.data.experimental.map_and_batch(map_func = 
parse, batch_size=batch_size))

我想嵌入像 [batch_size、max_words_in_batch、embedding_size] 这样的文本数组,但我收到一条错误消息:

"NotImplementedError: Using TF-Hub module within a TensorFlow defined 
 function is currently not supported."

怎样才能得到预期的结果?

遗憾的是,TensorFlow 不支持此功能1.x

但是,它在 TensorFlow 2.0 中受支持,因此如果您可以升级到 tensorflow 2 并从 tf 2 的可用文本嵌入模块中进行选择(当前列表 here),那么您可以在 dataset管道。像这样:

embedder = hub.load("https://tfhub.dev/google/tf2-preview/nnlm-en-dim128/1")

def parse(sentences):
    embeddings = embedder([sentences])
    return embeddings

dataset = tf.data.TextLineDataset("text.txt")
dataset = dataset.map(parse)

如果您绑定到 1.x 或绑定到 Elmo(我认为在新格式中尚不可用),那么我能看到的唯一嵌入预处理阶段的选项是首先运行 您的数据集通过一个简单的嵌入模型并保存结果,然后将嵌入向量分别用于下游任务。 (我很欣赏这不太理想)。