gpt4 book ai didi

python - 隐藏状态与 Tensorflow 的 dynamic_rnn 返回的最终状态

转载 作者:太空宇宙 更新时间:2023-11-03 15:45:53 26 4
gpt4 key购买 nike

tensorflow.nn.dynamic_rnn给定 cell 创建一个循环神经网络,它是 RNNCell 的一个实例,并返回一对包含:

  • outputs:RNN 输出张量
  • state:最终状态

这是一个玩具循环神经网络及其输出[*]:

import numpy as np
import tensorflow as tf

dim = 3
hidden = 4

lengths = tf.placeholder(dtype=tf.int32, shape=[None])
inputs = tf.placeholder(dtype=tf.float32, shape=[None, None, dim])
cell = tf.nn.rnn_cell.LSTMCell(hidden, state_is_tuple=True)
output, final_state = tf.nn.dynamic_rnn(
cell, inputs, lengths, dtype=tf.float32)

inputs_ = np.asarray([[[0, 0, 0], [1, 1, 1], [2, 2, 2]],
[[6, 6, 6], [7, 7, 7], [8, 8, 8]],
[[9,9,9], [10,10,10], [11,11,11]]],
dtype=np.int32)

lengths_ = np.asarray([3, 1, 2], dtype=np.int32)

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
output_, final_state_ = sess.run(
[output, final_state],
{inputs: inputs_, lengths: lengths_})

print('hidden states:')
print(output_)

print('final state :')
print(final_state_)

输出:

hidden states:
[[[ 0.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00]
[-3.0096283e-02 1.6747195e-01 2.3113856e-02 -4.5677904e-02]
[-6.0795926e-02 3.5036778e-01 6.0140129e-02 -1.6039203e-01]]

[[-2.1957003e-03 8.1749000e-02 1.2620161e-02 -2.8342882e-01]
[ 0.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00]
[ 0.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00]]

[[-1.7376180e-04 2.7789388e-02 3.1011081e-03 -3.5858861e-01]
[-2.5059914e-04 4.5771234e-02 4.5708413e-03 -6.5035087e-01]
[ 0.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00]]]

final state :
LSTMStateTuple(
c=array([[-1.0705842e-01, 5.2945197e-01, 1.5602852e-01, -2.5641304e-01],
[-3.3140955e-03, 8.6112522e-02, 7.2794281e-02, -3.6088336e-01],
[-3.4701003e-04, 4.6147645e-02, 6.7321308e-02, -8.6465287e-01]],
dtype=float32),
h=array([[-6.0795926e-02, 3.5036778e-01, 6.0140129e-02, -1.6039203e-01],
[-2.1957003e-03, 8.1749000e-02, 1.2620161e-02, -2.8342882e-01],
[-2.5059914e-04, 4.5771234e-02, 4.5708413e-03, -6.5035087e-01]],
dtype=float32))

我的理解是这样的:

  • 隐藏状态对应于批处理中每个序列在每个时间步的 LSTM 单元的输出;
  • 最终状态包含每个序列(c 组件)的最后一个单元状态以及每个序列(h 组件)的最后隐藏状态;

因此,我不应该在结局状态的 h 组件和每个序列的最后隐藏状态中获得相同的值吗?

[*] 代码主要灵感来自 this post

最佳答案

最终状态组件的 h 包含 LSTM 的最后输出,并且在 dynamic_rnn 的情况下它考虑了长度 作为参数 (lengths)

正如您在示例中看到的那样 final_state.h[0] 等于 output[0][2] ,因为第一个示例的长度是 3 , final_state.h[1] 等于 output[1][0] 因为你的第二个例子的长度是 1 等等。

关于python - 隐藏状态与 Tensorflow 的 dynamic_rnn 返回的最终状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49969349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com