Tensorflow tf.constant_initializer 很慢

Tensorflow tf.constant_initializer is very slow

尝试使用 100 dim 的预训练 word2vec 嵌入来训练 LSTM

@staticmethod
def load_embeddings(pre_trained_embeddings_path, word_embed_size):
    embd = []
    import time
    start_time = time.time()
    cnt = 4
    with codecs.open(pre_trained_embeddings_path, mode="r", encoding='utf-8') as f:
        for line in f.readlines():
            values = line.strip().split(' ')
            embd.append(values[1:])
            cnt += 1
            if cnt % 100000 == 0:
                print("word-vectors loaded: %d" % cnt)

    embedding, vocab_size, embed_dim = embd, len(embd), len(embd[0])

    load_end_time = time.time()
    print("word vectors loaded from and start initialising, cnt: %d, time taken: %d secs " % (vocab_size, load_end_time - start_time))

    embedding_init = tf.constant_initializer(embedding, dtype=tf.float16)
    src_word_embedding = tf.get_variable(shape=[vocab_size, embed_dim], initializer=embedding_init, trainable=False, name='word_embedding', dtype=tf.float16)

    print("word-vectors loaded and initialised, cnt: %d, time taken: %d secs" % (vocab_size, time.time() - load_end_time))

    return src_word_embedding

当 运行 这个方法的输出是这样的:

word vectors loaded from and start initialising, cnt: 2419080, time taken: 74 secs
word-vectors loaded and initialised, cnt: 2419080, time taken: 1647 secs

系统信息:tensorflow 1.1.0, tcmalloc, python 3.6, ubuntu 14.04

半小时初始化似乎很慢还是正常现象?知道可能是什么问题吗?

更新:使用@sirfz 提供嵌入的方法使得加载嵌入变得非常快Initialization Done in 85 secs

将大常量加载到图形中不仅速度较慢,而且还会泄漏大量内存。我有一个类似的问题I reported not long ago,对我来说最好的解决方法是:

# placeholder for loading your saved embeddings
embedding_init = tf.placeholder(tf.float16, shape=[vocab_size, embed_dim])
src_word_embedding = tf.get_variable(initializer=embedding_init, trainable=False, name='word_embedding', dtype=tf.float16)

# run initialization with the value of embeddings placeholder
session.run(tf.global_variables_initializer(), feed_dict={embedding_init: embedding})

我不知道这是否是预期的行为,但我可以用一个小例子来解释为什么它会变慢:

import tensorflow as tf

x = [[0, 1], [2, 3]]
a = tf.constant(x, name='a')
b = tf.Variable(x, name='b')
c = a + b

with tf.Session() as sess:
    writer = tf.summary.FileWriter('logs', sess.graph)
    writer.close()

当您初始化常量时,该常量的值将添加到图形中。如果您要打开图表,您可以通过单击 a 值来查看它。

在我的例子中它是一个 2x2 矩阵,但在你的例子中它看起来像是 2M x ?矩阵,很大。所以在我看来,这就是执行速度如此缓慢的原因。

尝试将其初始化为一个变量并将您嵌入其中。