今天终于弄明白,TensorFlow和Keras中LSTM神经网络的输入输出层到底应该怎么设置和连接了。写个备忘。

https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/

Stacked LSTM

Multiple hidden LSTM layers can be stacked one on top of another in what is referred to as a Stacked LSTM model.

An LSTM layer requires a three-dimensional input and LSTMs by default will produce a two-dimensional output as an interpretation from the end of the sequence.

We can address this by having the LSTM output a value for each time step in the input data by setting the return_sequences=True argument on the layer. This allows us to have 3D output from hidden LSTM layer as input to the next.

We can, therefore, define a Stacked LSTM as follows.

# define model
model = Sequential()
model.add(LSTM(50, activation='relu', return_sequences=True, input_shape=(n_steps, n_features)))
model.add(LSTM(50, activation='relu'))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
X_train.shape
(500, 40, 1)
y_train.shape
(500, 40, 1)
from keras.models import Sequential
from keras import layers
from keras.optimizers import RMSprop model = Sequential()
model.add(layers.GRU(100, input_shape=(None, X_train.shape[-1]), return_sequences=True))
model.add(layers.Dense(1))
model.compile(optimizer=RMSprop(), loss='mae')
history = model.fit(X_train, y_train,steps_per_epoch=25,epochs=20)
reset_graph()

n_steps = 40
n_inputs = 1
n_neurons = 100 X = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
y = tf.placeholder(tf.float32, [None, n_steps, n_outputs]) num_units = [500, 200, 100]
cells = [tf.nn.rnn_cell.GRUCell(num_units=n) for n in num_units]
stacked_rnn_cell = tf.nn.rnn_cell.MultiRNNCell(cells)
rnn_outputs, states = tf.nn.dynamic_rnn(stacked_rnn_cell, X, dtype=tf.float32) # 先去掉一个维度,用一个Dense层连上,再把n_steps这个维度加回去
# [batch_size, n_steps, n_neurons]
# [batch_size * n_steps, n_neurons]
# [batch_size, n_steps, n_neurons] stacked_rnn_outputs = tf.reshape(rnn_outputs, [-1, n_neurons])
stacked_outputs = tf.layers.dense(stacked_rnn_outputs, n_outputs)
outputs = tf.reshape(stacked_outputs, [-1, n_steps, n_outputs]) loss = tf.reduce_mean(tf.square(outputs - y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
training_op = optimizer.minimize(loss) init = tf.global_variables_initializer()
saver = tf.train.Saver() n_iterations = 5000
batch_size = 100 with tf.Session() as sess:
init.run()
for iteration in range(n_iterations):
X_batch, y_batch = next_batch(batch_size, n_steps)
sess.run(training_op, feed_dict={X: X_batch, y: y_batch})
if iteration % 100 == 0:
mse = loss.eval(feed_dict={X: X_batch, y: y_batch})
print(iteration, "\tMSE:", mse) X_new = time_series(np.array(t_instance[:-1].reshape(-1, n_steps, n_inputs)))
y_pred = sess.run(outputs, feed_dict={X: X_new}) saver.save(sess, "./my_time_series_model")
  • TensorFlow不同, Keras 中 LSTM 层默认只输出最后一个时间步

LSTM 神经网络输入输出层的更多相关文章

  1. LSTM神经网络输入输出究竟是怎样的?

    LSTM图和词向量输入分析

  2. LSTM神经网络

    LSTM是什么 LSTM即Long Short Memory Network,长短时记忆网络.它其实是属于RNN的一种变种,可以说它是为了克服RNN无法很好处理远距离依赖而提出的. 我们说RNN不能处 ...

  3. (转)LSTM神经网络介绍

    原文链接:http://www.atyun.com/16821.html 扩展阅读: https://machinelearningmastery.com/time-series-prediction ...

  4. (转) 干货 | 图解LSTM神经网络架构及其11种变体(附论文)

    干货 | 图解LSTM神经网络架构及其11种变体(附论文) 2016-10-02 机器之心 选自FastML 作者:Zygmunt Z. 机器之心编译  参与:老红.李亚洲 就像雨季后非洲大草原许多野 ...

  5. 关于LeNet-5卷积神经网络 S2层与C3层连接的参数计算的思考???

    https://blog.csdn.net/saw009/article/details/80590245 关于LeNet-5卷积神经网络 S2层与C3层连接的参数计算的思考??? 首先图1是LeNe ...

  6. MLP神经网络 隐含层节点数的设置】如何设置神经网络隐藏层 的神经元个数

    神经网络 隐含层节点数的设置]如何设置神经网络隐藏层 的神经元个数 置顶 2017年10月24日 14:25:07 开心果汁 阅读数:12968    版权声明:本文为博主原创文章,未经博主允许不得转 ...

  7. tensorflow学习之(十一)RNN+LSTM神经网络的构造

    #RNN 循环神经网络 import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data tf.se ...

  8. 深入浅出LSTM神经网络

    转自:https://www.csdn.net/article/2015-06-05/2824880 LSTM递归神经网络RNN长短期记忆   摘要:根据深度学习三大牛的介绍,LSTM网络已被证明比传 ...

  9. Tensorflow之基于LSTM神经网络写唐诗

    最近看了不少关于写诗的博客,在前人的基础上做了一些小的改动,因比较喜欢一次输入很长的开头句,所以让机器人输出压缩为一个开头字生成两个诗句,写五言和七言诗,当然如果你想写更长的诗句是可以继续改动的. 在 ...

随机推荐

  1. Retina 屏幕与二倍图

    分辨率 屏幕分辨率:指屏幕可显示的像素的个数 图像分辨率:位图图像包含的像素的个数 对于 Retina 屏它的分辨率是传统屏的两倍,而屏幕大小没有变化,所以它需要的图片的分辨率应该是传统屏幕的两倍(甚 ...

  2. django 给数据库批量添加数据

    from .models import Book import random def index(request): book_list = [] for i in range(1, 101): bo ...

  3. 2019 Nanchang Onsite

    D.Interesting Series F(n)实际上是一个等比数列的和,将它从递推式转变为通项公式(a^n-1)/(a-1),这里只需要确定n就可以. 题目要求选取k大小的所有子集的答案求和,可以 ...

  4. 阶段1 语言基础+高级_1-3-Java语言高级_03-常用API第二部分_第4节 System类_3_System类的常用方法

    复制数组

  5. 把数据库中的数据制作成Excel数据

    把数据库中的数据制作成Excel数据 如果我们在使用Excel的时候,需要把数据库中的数据制作成Excel数据透视表,我们该怎么操作呢?如果数据在数据库中,我们不用把数据导入到工作表中,我们可以直接以 ...

  6. 删除历史日志的一个API

    删除历史日志的一个API bool DeleteOldFiles(const char* strFolder, const char* strPrefix, bool is_recursion, UI ...

  7. Java 基础-异常处理

    在 Java 中声明了很多异常类,每个异常类都表示一种运行错误.程序运行过程中发生一个可识别的运行错误时(可以找到与错误匹配的异常类,例如被除数为 0 时会触发 java.lang.Arithmeti ...

  8. 【ABAP系列】SAP ABAP实现发送外部邮件(添加附件)功能

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[MM系列]SAP ABAP实现发送外部邮件(添 ...

  9. Struts2入门1

    Struts2的概述: Struts2是应用在Javaee三层结构中的web层.Struts2是在Struts1和webwork的基础之上发展的全新的框架.在没有使用Struts2之前,进行web层的 ...

  10. 2018年牛客多校寒假 第四场 F (call to your teacher) (图的连通性)

    题目链接 传送门:https://ac.nowcoder.com/acm/contest/76/F 思路: 题目的意思就是判断图的连通性可以用可达性矩阵来求,至于图的存储可以用邻接矩阵来储存,求出来可 ...