【问题标题】:Parameters computation of LSTMLSTM的参数计算
【发布时间】:2019-07-24 11:17:43
【问题描述】:

我正在尝试计算 LSTM 模型的总参数,我有些困惑。

我搜索了一些答案,例如this postthis post。我不知道隐藏单元在参数计算中的作用是什么(在我的例子中是 h1=64,h2=128)。

import tensorflow as tf

b, t, d_in, d_out = 32, 256, 161, 257

data = tf.placeholder("float", [b, t, d_in])  # [batch, timestep, dim_in]
labels = tf.placeholder("float", [b, t, d_out])  # [batch, timestep, dim_out]

myinput = data
batch_size, seq_len, dim_in = myinput.shape

rnn_layers = []

h1 = 64
c1 = tf.nn.rnn_cell.LSTMCell(h1)
rnn_layers.append(c1)

h2 = 128
c2 = tf.nn.rnn_cell.LSTMCell(h1)
rnn_layers.append(c2)

multi_rnn_cell = tf.nn.rnn_cell.MultiRNNCell(rnn_layers)
rnnoutput, state = tf.nn.dynamic_rnn(cell=multi_rnn_cell, 
inputs=myinput, dtype=tf.float32)

sess = tf.Session()
sess.run(tf.global_variables_initializer())

all_trainable_vars = tf.reduce_sum([tf.reduce_prod(v.shape) for v in tf.trainable_variables()])
print(sess.run(all_trainable_vars))

我用Tensorflow打印了参数总数,显示一个参数的总数是90880。我怎样才能一步一步得到这个结果,谢谢

【问题讨论】:

    标签: tensorflow deep-learning lstm


    【解决方案1】:

    在您的情况下,您通过此行 c1 = tf.nn.rnn_cell.LSTMCell(h1) 定义了一个 LSTM 单元。为了回答你的问题,这里我将介绍 LSTM 的数学定义。喜欢下图(图片来源wikipedia-lstm),

    t:表示时间t

    • f_t 被命名为遗忘门。
    • i_t 被命名为输入门。
    • o_t 被命名为被调用。
    • c_t, h_t 分别被命名为 LSTM 单元的单元状态和隐藏状态。

    对于tf.nn.rnn_cell.LSTMCell(h1)h1=64h_t的维度,即dim(h_t) = 64

    【讨论】:

    • 非常感谢您的解释。还有一件事,你知道我怎样才能得到最终结果 90880 吗?我的意思是,两层的 W、U、b 的尺寸是多少(h1=64,h2=128)?
    • 对不起,我弄错了。 c2 = tf.nn.rnn_cell.LSTMCell(h1)。它应该是 c2 = tf.nn.rnn_cell.LSTMCell(h2)。在我的情况下,对于第一层,总参数:4 * (64 * (64 + 161) + 64) = 57856,对于第二层,总参数:4 * (128 * (128 + 64) + 128) = 98816。总共是 57856 + 98816 = 156672,与 Tensorflow 打印的相同。
    猜你喜欢
    • 2021-04-20
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2020-08-20
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多