今天终于弄明白,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. 数据库缓存之Memcache知识点

    Memcache知识点总结: 一.Memcache安装及使用 参考地址:https://www.jb51.net/article/66525.htm 1.将下载的Memcache安装文件放到某盘下,如 ...

  2. accomplish、complete、finish、achieve和fulfill

    accomplish to succeed in doing something, especially after trying very hard vt. 完成:实现:达到 complete us ...

  3. ASP.NET Core 上传微信永久视频素材

    话不多说直接上源码 请求实体  public class AddVideoRequest    {        /// <summary>        /// 文件流        / ...

  4. 山西汽车销量(hive)

    1.创建数据库create database db_cart; 2.使用数据库use db_cart; 3.创建表create table t_cart(province STRING,month I ...

  5. SpringBoot整合SpringMVC完成文件上传

    1.编写Controller /** * SPringBoot文件上传 */ //@Controller @RestController //表示该类下的方法的返回值会自动做json格式的转换 pub ...

  6. 剑指offer--day05

    1.1 题目:二进制中1的个数:输入一个整数,输出该数二进制表示中1的个数.其中负数用补码表示. 1.2 解题思路:通过位移来进行.举例:7(二进制:0111),7 >> 1(得到:001 ...

  7. [LeetCode] 834. Sum of Distances in Tree

    LeetCode刷题记录 传送门 Description An undirected, connected treewith N nodes labelled 0...N-1 and N-1 edge ...

  8. promise 封装 axios

    /*axios({ method:"get", url:"./data.json", data:{ id:10 } }).then((res)=>{ co ...

  9. Linked List Cycle(链表成环)

    判断链表中是否有环 来源:https://leetcode.com/problems/linked-list-cycle Given a linked list, determine if it ha ...

  10. jquery悬停和移出事件

    $('#hides').mouseover(function () { alert("sdfdsf")}).mouseout(function () { alert("啊 ...