关于LSTM给大家推荐一篇讲解的十分好的博文:

难以置信!LSTM和GRU的解析从未如此清晰(动图+视频)

https://blog.csdn.net/dQCFKyQDXYm3F8rB0/article/details/82922386

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as pltBATCH_START = 0 #建立 batch data 时候的 index
TIME_STEPS = 20 # backpropagation through time 的time_steps
BATCH_SIZE = 50
INPUT_SIZE = 1 # x数据输入size
OUTPUT_SIZE = 1 # cos数据输出 size
CELL_SIZE = 10 # RNN的 hidden unit size
LR = 0.006  # learning rate# 定义一个生成数据的 get_batch function:
def get_batch():#global BATCH_START, TIME_STEPS# xs shape (50batch, 20steps)xs = np.arange(BATCH_START, BATCH_START+TIME_STEPS*BATCH_SIZE).reshape((BATCH_SIZE, TIME_STEPS)) / (10*np.pi)res = np.cos(xs)# returned  xs and res: shape (batch, step, input)return [xs[:, :, np.newaxis], res[:, :, np.newaxis]]# 定义 LSTMRNN 的主体结构
class LSTMRNN(object):def __init__(self, n_steps, input_size, output_size, cell_size, batch_size):self.n_steps = n_stepsself.input_size = input_sizeself.output_size = output_sizeself.cell_size = cell_sizeself.batch_size = batch_sizewith 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(LR).minimize(self.cost)# 设置 add_input_layer 功能, 添加 input_layer: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')# 设置 add_cell 功能, 添加 cell, 注意这里的 self.cell_init_state,#  因为我们在 training 的时候, 这个地方要特别说明.def add_cell(self):lstm_cell = tf.contrib.rnn.BasicLSTMCell(self.cell_size, forget_bias=1.0, state_is_tuple=True)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)# 设置 add_output_layer 功能, 添加 output_layer: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# 添加 RNN 中剩下的部分: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)# 训练 LSTMRNN
if __name__ == '__main__':# 搭建 LSTMRNN 模型model = LSTMRNN(TIME_STEPS, INPUT_SIZE, OUTPUT_SIZE, CELL_SIZE, BATCH_SIZE)sess = tf.Session()saver=tf.train.Saver(max_to_keep=3)sess.run(tf.global_variables_initializer())  t = 0   if(t == 1):model_file=tf.train.latest_checkpoint('model/')saver.restore(sess,model_file )xs, res = get_batch()  # 提取 batch datafeed_dict = {model.xs: xs}pred = sess.run( model.pred,feed_dict=feed_dict)xs.shape = (-1,1)res.shape = (-1, 1)pred.shape = (-1, 1)print(xs.shape,res.shape,pred.shape)plt.figure()plt.plot(xs,res,'-r')plt.plot(xs,pred,'--g')        plt.show()else: # matplotlib可视化plt.ion()  # 设置连续 plotplt.show()     # 训练多次for i in range(2500):xs, res = get_batch()  # 提取 batch data# 初始化 datafeed_dict = {model.xs: xs,model.ys: res,}           # 训练_, cost, state, pred = sess.run([model.train_op, model.cost, model.cell_final_state, model.pred],feed_dict=feed_dict)# plottingx = xs.reshape(-1,1)r = res.reshape(-1, 1)p = pred.reshape(-1, 1)plt.clf()plt.plot(x, r, 'r', x, p, 'b--')plt.ylim((-1.2, 1.2))plt.draw()plt.pause(0.3)  # 每 0.3 s 刷新一次# 打印 cost 结果if i % 20 == 0:saver.save(sess, "model/lstem_text.ckpt",global_step=i)#print('cost: ', round(cost, 4))

x值较小的点先收敛,x值大的收敛速度很慢。其原因主要是BPTT的求导过程,对于时间靠前的梯度下降快

将网络结构改为双向循环神经网络可以改善这个问题。

def add_cell(self):lstm_cell = tf.contrib.rnn.BasicLSTMCell(self.cell_size, forget_bias=1.0, state_is_tuple=True)lstm_cell = tf.contrib.rnn.MultiRNNCell([lstm_cell],1)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)

对于分类问题,其实和回归是一样的,假设在上面的正弦函数的基础上,若y大于0标记为1,y小于0标记为0,则输出变成了一个n_class(n个类别)的向量,本例中两个维度分别代表标记为0的概率和标记为1的概率。

需要修改的地方为:

首先是数据产生函数,添加一个打标签的过程:

# 定义一个生成数据的 get_batch function:
def get_batch():#global BATCH_START, TIME_STEPS# xs shape (50batch, 20steps)xs = np.arange(BATCH_START, BATCH_START+TIME_STEPS*BATCH_SIZE).reshape((BATCH_SIZE, TIME_STEPS)) / (200*np.pi)res = np.where(np.cos(4*xs)>=0,0,1).tolist()for i in range(BATCH_SIZE):for j in range(TIME_STEPS):           res[i][j] = [0,1] if res[i][j] == 1 else [1,0]# returned  xs and res: shape (batch, step, input/output)return [xs[:, :, np.newaxis], np.array(res)]

然后修改损失函数,回归问题就不能用最小二乘的损失了,可以采用交叉熵损失函数:

def compute_cost(self):self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = self.ys,logits = self.pred))

LSTM拟合正弦曲线代码(转载)相关推荐

  1. 【梯度下降法】Python 梯度下降法拟合正弦曲线 多项式函数傅里叶函数

    问题: 梯度下降法拟合正弦曲线   此处以三次函数为例,其他的函数拟合同理     1.梯度下降法原理   梯度下降相关公式   拟 合 的 函 数 : h ( x ) = ∑ i = 0 n θ i ...

  2. matlab数值分析拟合实例,数值分析函数拟合matlab代码.doc

    数值分析函数拟合matlab代码.doc 第一题MATLAB代码用SPLINE作图XI0204060810YI098092081064038X10012Y1NEWTON3XI,YI,X源代码见M文件Y ...

  3. 利用BP神经网络教计算机进行非线函数拟合(代码部分多层)

    利用BP神经网络教计算机进行非线函数拟合(代码部分多层) 本图文已经更新,详细地址如下: http://blog.csdn.net/lsgo_myp/article/details/54425751

  4. 决策树概述+模块介绍+重要参数(criterion+random_statesplitter+减枝参数+目标权重参数)+回归树(参数+实例+拟合正弦曲线)+泰坦尼克号生存者预测实例

    文章目录 什么是sklearn 一.决策树概述 (一)概述 (二)基础概念 (三)决策树算法的核心是要解决两个问题: 二.模块sklearn.tree的使用 (一) 模块介绍 (二)使用介绍 三.重要 ...

  5. matlab使用自带的拟合工具cftool对数据进行拟合并生成拟合函数代码

    在数据处理中经常会需要对数据进行拟合,拟合完成之后可以通过拟合曲线的方程对数据进行预测.下面主要介绍一下如何适用matlab自带的拟合工具包对数据进行拟合,全程不需要编写一句代码,拟合完成之后还能生成 ...

  6. LSTM/GRU详细代码解析+完整代码实现

    LSTM和GRU目前被广泛的应用在各种预测场景中,并与卷积神经网络CNN或者图神经网络GCN这里等相结合,对数据的结构特征和时序特征进行提取,从而预测下一时刻的数据.在这里整理一下详细的LSTM/GR ...

  7. 教你搭建多变量时间序列预测模型LSTM(附代码、数据集)

    来源:机器之心 本文长度为2527字,建议阅读5分钟 本文为你介绍如何在Keras深度学习库中搭建用于多变量时间序列预测的LSTM模型. 长短期记忆循环神经网络等几乎可以完美地模拟多个输入变量的问题, ...

  8. ASP.NET程序中常用的三十三种代码(转载)

    asp.net程序中最常用的三十三种编程代码,为初学者多多积累经验,为高手们归纳总结,看了觉得很有价值~,大家不妨参考下! 1. 打开新的窗口并传送参数: 传送参数: response.write(& ...

  9. tensorflow 最小二乘拟合详细代码注释

    #程序 不是我写的,注释是我做的,转载请注明"lg土木设计"#最小二乘法拟合,用y=ax+b a=weight b=biases from __future__ import pr ...

最新文章

  1. adg oracle 架构_云化双活的架构演进,宁夏银行新核心搭载Oracle 19c投产上线
  2. ELK实时分析之php的laravel项目日志
  3. 在Ubuntu系统中安装Docker
  4. node 版本升级_Node-RED: 自动化事件触发工具的安装与介绍
  5. python代码进去docker容器内_python脚本监控docker容器
  6. Radware:应用交付向云端扩展
  7. github-仓库基本-下载-上传
  8. 详解Javascript中的Array对象
  9. 巴菲特:我们会在中国找到机会
  10. 铝电解电容总结[转]
  11. 搜索框键盘抬起事件2
  12. 软件测试项目案例哪里找?【银行/教育/商城/金融/等等....】
  13. jQueryphotoClip-图片上传并裁剪
  14. 剁手节致敬!听当年的老人讲述阿帕网(互联网前身)诞生的故事
  15. 常见的手机端头部banner切换代码设置
  16. python break函数用法_Python break用法详解
  17. 360浏览器用地址栏搜索怎么更改搜索引擎
  18. 在线解压-密码压缩包
  19. Linux平台Java环境中文编码研究
  20. 永远的错误,不理解的结果

热门文章

  1. rejection foruc berkeley ece
  2. 别人给你网盘分享东西怎么搞到电脑上看呢?
  3. 刚毕业的参加工作的黄金时期的核心策略:打好基础
  4. ROBOMASTER 2018机甲大师赛 南部赛区三等奖!
  5. 在线版本powerbi的使用!开启您的商业智能!
  6. 哥伦比亚大学计算机工程面试题
  7. UNITY 手游(安卓)如何使用C/C++代码
  8. IOS FRAMEWORK,动态库 等几个问题
  9. 阿里云马劲:保证云产品持续拥有稳定性的实践和思考
  10. 从零开始学 Web 之 DOM(六)为元素绑定与解绑事件