tensorflow 循环神经网络RNN

来源:互联网 发布:意大利语发音软件 编辑:程序博客网 时间:2024/05/16 02:13
# 定义一个 LSTM 结构,LSTM 中使用的变量会在该函数中自动被声明
lstm = tf.contrib.rnn.BasicLSTMCell(lstm_hidden_size)

# 将 LSTM 中的状态初始化为全 0 数组,batch_size 给出一个 batch 的大小
state = lstm.zero_state(batch_size, tf.float32)

# 定义损失函数
loss = 0.0

# num_steps 表示最大的序列长度
for i in range(num_steps): 
     # 在第一个时刻声明 LSTM 结构中使用的变量,在之后的时刻都需要服用之前定义好的变量
     if i>0: 
         tf.get_variable_scope().reuse_variables() 

          # 每一步处理时间序列中的一个时刻。将当前输入(current_input)和前一时刻状态(state)传入定义的 LSTM 结构就可以得到当前 LSTM 结构的输出 lstm_output 和更               新后的状态 
      state lstm_output, state = lstm(current_input, state) 

     # 将当前时刻 LSTM 结构的输出传入一个全连接层得到最后的输出 
     final_output = fully_connected(lstm_output) 
 
     # 计算当前时刻输出的损失
     loss += calc_loss(final_output, expected_output)





链接:http://www.jianshu.com/p/3dbeb3ab9aa3

原创粉丝点击