Tensorflow-LSTMRNN例子

本文介绍了一个使用RNN预测波形序列的例子,通过构建LSTM RNN模型来预测sin和cos序列,并展示了如何训练模型及可视化预测结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Rnn预测一段波形的序列

导入模块

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.contrib import rnn

设置参数

batch_start = 0 #建立batch_data 的索引
time_steps = 20 #反向传播通过时间的time_steps
batch_size = 50
training_steps = 200
input_size = 1 #sin 数据输入 size
output_size = 1 #cos 数据输出 size
cell_size = 10 #RNN的隐藏单位的大小
learning_rate = 0.001 # 学习率

生成数据

def get_batch():
    global batch_start,time_steps
    # sx ==>(50batch, 20steps) 时间点Data
    sx = np.arange(batch_start,batch_start+time_steps*batch_size)
           .reshape((batch_size,time_steps))/(10*np.pi)
    seq = np.sin(sx)
    res = np.cos(sx)
    batch_start += time_steps
    # return shape==> (batch, step, input)
    return [seq[:, :, np.newaxis], res[:, :, np.newaxis], sx]

定义LTSMRNN主体结构

class LSTMRNN(object):
    def __init__(self, n_steps, input_size, output_size, cell_size, batch_size):
        self.n_steps = n_steps
        self.input_size = input_size
        self.output_size = output_size
        self.cell_size = cell_size
        self.batch_size = batch_size
        with tf.name_scope('inputs'):
            self.xs = tf.placeholder(tf.float32, [None, n_steps, input_size], name='xs')
            self.ys = tf.placeholder(tf.float32, [None, n_steps, output_size], name='ys')
        with tf.variable_scope('in_hidden'):
            self.add_input_layer()
        with tf.variable_scope('LSTM_cell'):
            self.add_cell()
        with tf.variable_scope('out_hidden'):
            self.add_output_layer()
        with tf.name_scope('cost'):
            self.compute_cost()
        with tf.name_scope('train'):
            self.train_op = tf.train
                            .AdamOptimizer(learning_rate)
                            .minimize(self.cost)

添加输入层

def add_input_layer(self):
    l_in_x = tf.reshape(self.xs, [-1, self.input_size], name='2_2D')  # (batch*n_step, in_size)
    # Ws (in_size, cell_size)
    Ws_in = self._weight_variable([self.input_size, self.cell_size])
    # bs (cell_size, )
    bs_in = self._bias_variable([self.cell_size,])
    # l_in_y = (batch * n_steps, cell_size)
    with tf.name_scope('Wx_plus_b'):
        l_in_y = tf.matmul(l_in_x, Ws_in) + bs_in
    # reshape l_in_y ==> (batch, n_steps, cell_size)
    self.l_in_y = tf.reshape(l_in_y, [-1, self.n_steps, self.cell_size], name='2_3D')

添加RNN的cell

def add_cell(self):
    lstm_cell = rnn.BasicLSTMCell(self.cell_size)
    with tf.name_scope('initial_state'):
        self.cell_init_state = lstm_cell.zero_state(self.batch_size, dtype=tf.float32)
    self.cell_outputs, self.cell_final_state = tf.nn.dynamic_rnn(lstm_cell, self.l_in_y, initial_state=self.cell_init_state, time_major=False)

添加输出层

def add_output_layer(self):
    # shape ==> (batch * steps, cell_size)
    l_out_x = tf.reshape(self.cell_outputs, [-1, self.cell_size], name='2_2D')
    Ws_out = self._weight_variable([self.cell_size, self.output_size])
    bs_out = self._bias_variable([self.output_size, ])
    # shape = (batch * steps, output_size)
    with tf.name_scope('Wx_plus_b'):
        self.pred = tf.matmul(l_out_x, Ws_out) + bs_out

计算损失和评估模型

def compute_cost(self):
    losses = tf.contrib.legacy_seq2seq.sequence_loss_by_example(
                    [tf.reshape(self.pred, [-1], name='reshape_pred')],
                    [tf.reshape(self.ys, [-1], name='reshape_target')],
                    [tf.ones([self.batch_size * self.n_steps], dtype=tf.float32)],
                    average_across_timesteps=True,
                    softmax_loss_function=self.ms_error,
                    name='losses'
    )
    with tf.name_scope('average_cost'):
        self.cost = tf.div( tf.reduce_sum(losses, name='losses_sum'), self.batch_size,name='average_cost')
        tf.summary.scalar('cost', self.cost)

def ms_error(self, labels, logits):
    return tf.square(tf.subtract(labels, logits))

定义权重变量

def _weight_variable(self, shape, name='weights'):
    initializer = tf.random_normal_initializer(mean=0., stddev=1.,)
    return tf.get_variable(shape=shape, initializer=initializer, name=name)

定义偏置变量

def _bias_variable(self, shape, name='biases'):
    initializer = tf.constant_initializer(0.1)
    return tf.get_variable(name=name, shape=shape, initializer=initializer)

开始训练测试

if __name__ == '__main__':
    model = LSTMRNN(time_steps, input_size, output_size, cell_size, batch_size)
    with tf.Session() as sess:
        #tensorboard
        merged = tf.summary.merge_all()
        writer = tf.summary.FileWriter("logs", sess.graph)
        sess.run(tf.global_variables_initializer())
        plt.ion()
        plt.show()
        for i in range(training_steps):
            seq, res, xs = get_batch()  # 提取 batch data
            if i == 0:
                # create initial state
                feed_dict = {
                    model.xs: seq,
                    model.ys: res
                }

            else :
                # use last state as the initial state for this run
                feed_dict = {
                    model.xs: seq,
                    model.ys: res,
                    model.cell_init_state: state
                }

            _, cost, state, pred = sess.run( [model.train_op, model.cost, model.cell_final_state, model.pred],feed_dict=feed_dict)

            # 画线
            plt.plot(xs[0, :], res[0].flatten(), 'r', xs[0, :], pred.flatten()[:time_steps], 'b--')
            plt.ylim((-1.2, 1.2))
            plt.draw()
            plt.pause(0.3)

            if i % 20 == 0:
                print('cost: ', round(cost, 4))
                result = sess.run(merged, feed_dict)
                writer.add_summary(result, i)

运输结果:
输出的波形图结果
计算的偏差概率
上面两幅图都是数据上的展示 从波形图看,LSTMRNN的准确度越来越高,基本已经和sin曲线吻合了。计算的偏差也是越来越低,偏差小于0.1。
在tensorboard可以看到神经图,图的结构如下:
lstm结构图
图的左边就是这个例子的LSTMRNN的组成结构 有三层的layer组成,两个hidden layer (input/output)+一个cell。
展开这三个layer
这里写图片描述

hidden layer 包括一个权重和偏执和输入数据,在inputer layer的输入数据先转成二维的数据在输出成3维的数据,在output layer中将cell输出的数据再转成二维数据再经过Wx_plus_b输出结果。
在cell中包括一个rnn的cell和一个initial_state,initial_state在每一次batch循环时被final_state代替。
tf中的bppt如下:
这里写图片描述

<think>好的,我现在需要回答用户关于RNN和LSTM的差异与应用场景的问题。首先,我得先回顾一下RNN和LSTM的基本概念。 用户提供的引用中有提到,RNN是处理序列数据的,比如时间序列或文本,它们有内部循环连接,可以记住前序信息[^1]。而LSTM是RNN的一种变体,结构更复杂,有四个交互层,包括Sigmoid和tanh激活函数,用来解决长期依赖问题[^3][^4]。我需要比较两者的结构差异,比如RNN只有单一的神经网络层重复,而LSTM有四个层,这样的结构差异如何影响它们的记忆能力。 接下来是梯度问题。用户可能想知道为什么RNN会有梯度消失或爆炸的问题。根据知识,RNN在反向传播时,梯度会随时间步长连乘,导致梯度不稳定。而LSTM通过门控机制(遗忘门、输入门、输出门)来控制信息的流动,从而缓解这个问题。需要具体说明这些门的作用,比如遗忘门决定保留多少旧信息,输入门决定新增多少新信息,这样能有效管理记忆[^4]。 应用场景方面,RNN适合处理较短的序列,比如文本生成或时间序列预测,但可能在长序列上表现不佳。LSTM因为能捕捉长期依赖,更适合机器翻译、语音识别等需要长距离信息的任务。需要举一些例子,比如RNN用于简单的时间序列预测,而LSTM用于翻译或生成较长的文本。 另外,用户可能对实现代码感兴趣。需要给出简单的示例,比如RNN的循环结构和LSTM的门控实现。比如用PyTorch或者TensorFlow的代码片段,展示两者的层结构差异,比如LSTM有更多的参数和门控计算。 还要注意引用用户提供的资料,比如引用[4]提到LSTM的结构差异和门控机制,引用[1]关于RNN的基本原理。确保在回答中正确标注引用来源。 最后,生成的相关问题需要围绕两者的比较、优化、具体应用等,比如为什么LSTM能解决梯度消失,或者在实际项目中如何选择RNN和LSTM。 需要检查是否符合格式要求:行内公式用$...$,独立公式用$$...$$,正确的中文回答,结构清晰,分点说明差异和应用场景,代码用代码块,相关问题在最后列出。</think>### RNN与LSTM的差异与应用场景 #### 1. **核心差异** - **结构差异** - **RNN**:通过单一的循环层处理序列数据,每个时间步的隐藏状态$h_t$由当前输入$x_t$和前一步的隐藏状态$h_{t-1}$决定: $$h_t = \tanh(W_{xh}x_t + W_{hh}h_{t-1} + b_h)$$ 这种简单结构导致难以捕捉长距离依赖。 - **LSTM**:引入**门控机制**(遗忘门、输入门、输出门)和**细胞状态(Cell State)**,通过以下公式控制信息流: - 遗忘门:$f_t = \sigma(W_f \cdot [h_{t-1}, x_t] + b_f)$ - 输入门:$i_t = \sigma(W_i \cdot [h_{t-1}, x_t] + b_i)$ - 候选记忆:$\tilde{C}_t = \tanh(W_C \cdot [h_{t-1}, x_t] + b_C)$ - 更新细胞状态:$C_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t$ - 输出门:$o_t = \sigma(W_o \cdot [h_{t-1}, x_t] + b_o)$ - 最终输出:$h_t = o_t \odot \tanh(C_t)$ 通过门控机制,LSTM能选择性保留或遗忘信息,解决梯度消失问题。 - **梯度问题** - RNN在长序列中因梯度连乘导致梯度消失或爆炸,难以学习长期依赖。 - LSTM通过细胞状态的线性传播路径($C_t$更新公式中的$f_t \odot C_{t-1}$)保持梯度稳定,更适合长序列任务[^4]。 #### 2. **应用场景对比** | **场景** | **RNN适用性** | **LSTM适用性** | |-------------------------|----------------------------------|-----------------------------------| | **短序列任务** | ✅ 如时间序列预测、简单文本分类 | ✅ 但可能性能过剩 | | **长序列任务** | ❌ 易丢失早期信息 | ✅ 如机器翻译、文档摘要、语音识别 | | **实时性要求高** | ✅ 计算量小,推理速度快 | ❌ 参数量大,计算成本较高 | | **需捕捉长期依赖的任务**| ❌ 如生成连贯段落、视频分析 | ✅ 通过门控机制有效管理记忆 | #### 3. **代码实现示例** - **RNN的简单实现(PyTorch)** ```python import torch.nn as nn class SimpleRNN(nn.Module): def __init__(self, input_size, hidden_size): super().__init__() self.rnn = nn.RNN(input_size, hidden_size, batch_first=True) def forward(self, x): output, _ = self.rnn(x) # output包含所有时间步的隐藏状态 return output ``` - **LSTM的实现(PyTorch)** ```python class SimpleLSTM(nn.Module): def __init__(self, input_size, hidden_size): super().__init__() self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True) def forward(self, x): output, (h_n, c_n) = self.lstm(x) # h_n为最终隐藏状态,c_n为细胞状态 return output ``` #### 4. **关键总结** - **选择RNN的场景**:序列较短、资源受限(如嵌入式设备)、实时性要求高。 - **选择LSTM的场景**:需处理长序列依赖(如翻译、生成文本)、对精度要求高且计算资源充足[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值