我有一个 TensorflowDatasetV1Adapter
对象形式的数据集。
<DatasetV1Adapter shapes: OrderedDict([(labels, (6,)), (snippets, ())]), types: OrderedDict([(labels, tf.int32), (snippets, tf.string)])>
# Example Output
OrderedDict([('labels', <tf.Tensor: id=37, shape=(6,), dtype=int32, numpy=array([0, 0, 0, 0, 0, 0], dtype=int32)>), ('snippets', <tf.Tensor: id=38, shape=(), dtype=string, numpy=b'explanationwhy the edits made under my username hardcore metallica fan were reverted they werent vandalisms just closure on some gas after i voted at new york dolls fac and please dont remove the template from the talk page since im retired now892053827'>)])
OrderedDict([('labels', <tf.Tensor: id=41, shape=(6,), dtype=int32, numpy=array([0, 0, 0, 0, 0, 0], dtype=int32)>), ('snippets', <tf.Tensor: id=42, shape=(), dtype=string, numpy=b'daww he matches this background colour im seemingly stuck with thanks talk 2151 january 11 2016 utc'>)])
如您所见,它包含一个带有和OrderedDict
键的对象。后者基本上很重要,因为它包含我希望使用句子嵌入将其转换为向量的文本字符串。labels
snippets
为此,我决定使用来自 tensorflow hub的Universal Sentence Encoder (USE)。它基本上接受一个句子列表作为输入,并将输出一个长度为 512 的向量作为其输出。需要注意的一件事是,如果启用了急切执行,则无法执行 tensorflow hub。因此,我们必须定义一个会话才能将 USE 与 tensorflow hub 一起使用。
但是,我希望使用map
tensorflow 提供的。但问题是我应该如何定义一个在其中包含 tensorflow 会话的函数?并且要使用该函数并将其映射到数据集上,我是否需要定义另一个 tensorflow 会话?
我的第一种方法是真正做到这一点。具体来说,通过定义一个包含 tensorflow 会话的函数。然后,启动一个新的 tensorflow 会话并尝试将函数映射到该会话中的该数据集。
请注意,我在会话之外定义了 USE 句子嵌入模型。
# Sentence embedding model (USE)
embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder/2")
def to_vec(w):
x = w['snippets']
with tf.Session() as sess:
vector = sess.run(embed(x))
return vector
with tf.Session() as sess:
sess.run([tf.global_variables_initializer(), tf.tables_initializer()])
# try_data is the DatasetV1Adapter object
sess.run(try_data.map(to_vec))
但我最后得到了这个错误
RuntimeError: Module must be applied in the graph it was instantiated for.
或者,我尝试在 tensorflow 会话中定义函数,就像这样
with tf.Session() as sess:
sess.run([tf.global_variables_initializer(), tf.tables_initializer()])
def to_vec(w):
x = w['snippets']
vector = sess.run(embed(x))
return vector
sess.run(try_data.map(to_vec))
但这没有用,我仍然遇到同样的错误。在做了一些搜索之后,我偶然发现了这篇文章和这篇文章,说我必须定义 atf.Graph
并在会话中传递它。
graph = tf.Graph()
with graph.as_default():
with tf.Session(graph=graph) as sess:
sess.run([tf.global_variables_initializer(), tf.tables_initializer()])
def to_vec(w):
x = w['snippets']
vector = sess.run(embed(x))
return vector
sess.run(try_data.map(to_vec))
然而,我仍然收到同样的错误。我还尝试在会话中定义 USE ,但仍然导致相同的错误。
从那里开始,我对如何做到这一点感到很困惑。有人对我错过的东西有任何想法吗?提前致谢。