我目前正试图比较数以百万计的文件的相似性。在CPU上进行第一次测试时,我将每个字符减少到大约50个字符,并尝试在这样的情况下为其中10个字符获得ELMo嵌入:
ELMO = "https://tfhub.dev/google/elmo/2"
for row in file:
split = row.split(";", 1)
if len(split) > 1:
text = split[1].replace("\n", "")
texts.append(text[:50])
if i == 300:
break
if i % 10 == 0:
elmo = hub.Module(ELMO, trainable=False)
executable = elmo(
texts,
signature="default",
as_dict=True)["elmo"]
vectors = execute(executable)
texts = []
i += 1然而,即使使用这个小示例,在大约300句语句(甚至不保存向量)之后,程序也会消耗高达12 of的RAM。这是一个已知的问题(我发现的其他问题表明了类似的问题,但没有那么极端),还是我犯了一个错误?
发布于 2019-06-07 11:15:50
我认为,这是针对没有急切模式的TensorFlow 1.x (否则,hub.Module的使用可能会遇到更大的问题)。
在该编程模型中,首先需要用TensorFlow图表示计算,然后对每一批数据重复执行该图。
hub.Module()构造模块,并将其应用于将输入张量映射到输出张量的过程中,都是图形生成的一部分,应该只发生一次。幸运的是,已经有一个实用程序函数可以为您完成所有这些工作:
import numpy as np
import tensorflow_hub as hub
# For demo use only. Extend to your actual I/O needs as you see fit.
inputs = (x for x in ["hello world", "quick brown fox"])
with hub.eval_function_for_module("https://tfhub.dev/google/elmo/2") as f:
for pystr in inputs:
batch_in = np.array([pystr])
batch_out = f(batch_in)
print(pystr, "--->", batch_out[0])就原始TensorFlow而言,这对您所做的大概是这样的:
module = Module(ELMO_OR_WHATEVER)
tensor_in = tf.placeholder(tf.string, shape=[None]) # As befits `module`.
tensor_out = module(tensor_in)
# This kind of session handles init ops for you.
with tf.train.SingularMonitoredSession() as sess:
for pystr in inputs:
batch_in = np.array([pystr])
batch_out = sess.run(tensor_out, feed_dict={tensor_in: batch_in}
print(pystr, "--->", batch_out[0])如果您的需求对于with hub.eval_function_for_module ...来说太复杂了,您可以构建这个更明确的示例。
注意如何在循环中既不构造也不调用hub.Module。
PS:厌倦了担心构建图表还是运行会话?那么TF2和急切的执行是为您准备的。查看classification.ipynb
https://stackoverflow.com/questions/56488857
复制相似问题