Tensorflow keras.LSTM展开会减慢梯度计算

时间:2019-12-09 02:41:28

标签: python tensorflow keras lstm unroll

因此,我认为展开LSTM应该可以直观地并且由于this而加快速度:

  

unroll:布尔值(默认为False)。如果为True,则网络将是   展开,否则将使用符号循环。展开可以加快   RNN,尽管它往往会占用更多的内存。仅展开   适合短序列。

好吧,考虑这段代码:

import time
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras

tf.compat.v1.disable_v2_behavior()


def test(unroll):
    inp = tf.compat.v1.placeholder(tf.float32, shape=(None, 300 if unroll else None, 256))
    lstm = keras.layers.LSTM(256, unroll=unroll)
    loss = lstm(inp)[0, 0]
    gradient = tf.gradients(loss, lstm.trainable_weights)

    with tf.compat.v1.Session() as sess:
        sess.run(tf.compat.v1.global_variables_initializer())
        st = time.time()
        sess.run([gradient], {inp: np.ones((1, 300, 256))})
        print(f'{time.time() - st}')

运行test(True)会产生7.193859100341797,而运行test(False)则会打印0.35205936431884766。我在这里做错什么了吗?

我已经使用python 3.6.8上的TF 1.15.0和python 3.6.9上的TF 2.0.0进行了测试。

0 个答案:

没有答案