今天终于弄明白,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. Java的参数传递是值传递?

    引用传递和值传递的区别.(不先说定义的都是在耍流氓!) 按值调用(call by value) : 在参数传递过程中,形参和实参占用了两个完全不同的内存空间.形参所存储的内容是实参存储内容的一份拷贝. ...

  2. Using Groovy To Import XML Into MongoDB

    w https://trishagee.github.io/post/groovy_import_to_mongodb/

  3. create react app的 css loader 进行局部配置

    { test: cssRegex, exclude: cssModuleRegex, use: getStyleLoaders({ importLoaders: 1, sourceMap: isEnv ...

  4. 004-spring-data-elasticsearch 3.0.0.0使用【二】-spring-data之定义方法、创建repository实例、从聚合根发布事件

    续上文 1.4.定义方法 存储库代理有两种方法可以从方法名称派生特定于存储的查询.它可以直接从方法名称派生查询,或者使用手动定义的查询.可用选项取决于实际store.但是,必须有一个策略来决定创建什么 ...

  5. sklearn版本

    10.19.0以前的sklearn版本才有cross_validation包,这个时候不要用model_selection导入StratifiedKFold,要用cross_validation,0. ...

  6. golang md5 结果类型

    golang  md5 结果类型 package main import ( "crypto/md5" "encoding/hex" "fmt&quo ...

  7. 【Android Studio安装部署系列】十三、Android studio添加和删除Module 2

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 概述 新建.导入.删除Module是常见的操作,这里简单介绍下. 新建Module File——New——New Module... 选中 ...

  8. C# picturebox 加载图片后透明显示在另一控件之上

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  9. STL 配接器(adapters)

    定义 配接器(adapters):将一个class的接口,转换为另一个class的接口,使得原来不能一起使用相互兼容的classes,可以一起协同工作. 配接器是一种设计模式. STL中提供的各种配接 ...

  10. 极*Java速成教程 - (3)

    Java语言基础 访问权限控制 Java是一个面向对象的语言,当你不是它所设计的要面向的对象时,它就不会给你看你不该看到的东西,也就是"访问权限控制". 亲疏有别,才能权限控制 包 ...