TF之LSTM:利用基于顺序的LSTM回归算法对DIY数据集sin曲线(蓝虚)预测cos(红实)(matplotlib动态演示)—daiding

简介: TF之LSTM:利用基于顺序的LSTM回归算法对DIY数据集sin曲线(蓝虚)预测cos(红实)(matplotlib动态演示)—daiding

输出结果

image.png





代码设计


import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt

BATCH_START = 0  

TIME_STEPS = 20    

BATCH_SIZE = 50    

INPUT_SIZE = 1      

OUTPUT_SIZE = 1    

CELL_SIZE = 10      

LR = 0.006      

BATCH_START_TEST = 0

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)

   seq = np.sin(xs)

   res = np.cos(xs)

   BATCH_START += TIME_STEPS

   return [seq[:, :, np.newaxis], res[:, :, np.newaxis], xs]

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(LR).minimize(self.cost)

         

   def add_input_layer(self,):  

       l_in_x = tf.reshape(self.xs, [-1, self.input_size], name='2_2D')

       Ws_in = self._weight_variable([self.input_size, self.cell_size])

       bs_in = self._bias_variable([self.cell_size,])

       with tf.name_scope('Wx_plus_b'):

           l_in_y = tf.matmul(l_in_x, Ws_in) + bs_in

       self.l_in_y = tf.reshape(l_in_y, [-1, self.n_steps, self.cell_size], name='2_3D')

     

   def add_cell(self):      

       lstm_cell = tf.nn.rnn_cell.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)  

         

   def add_output_layer(self):  

       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, ])

       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, y_target, y_pre):  

       return tf.square(tf.sub(y_target, y_pre))

   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)

   sess = tf.Session()

   merged=tf.summary.merge_all()

   writer=tf.summary.FileWriter("niu0127/logs0127",sess.graph)

   sess.run(tf.initialize_all_variables())

 

plt.ion()  

plt.show()

 

for i in range(200):

     seq, res, xs = get_batch()

     if i == 0:

         feed_dict = {

                 model.xs: seq,

                 model.ys: res,

         }

     else:

         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],'g--')

     plt.title('Matplotlib,RNN,Efficient learning,Approach,Cosx --Jason Niu')

     plt.ylim((-1.2,1.2))

     plt.draw()

     plt.pause(0.1)  



相关文章
|
机器学习/深度学习 算法 数据挖掘
K-means聚类算法是机器学习中常用的一种聚类方法,通过将数据集划分为K个簇来简化数据结构
K-means聚类算法是机器学习中常用的一种聚类方法,通过将数据集划分为K个簇来简化数据结构。本文介绍了K-means算法的基本原理,包括初始化、数据点分配与簇中心更新等步骤,以及如何在Python中实现该算法,最后讨论了其优缺点及应用场景。
1270 6
|
11月前
|
机器学习/深度学习 算法 数据可视化
利用SVM(支持向量机)分类算法对鸢尾花数据集进行分类
本文介绍了如何使用支持向量机(SVM)算法对鸢尾花数据集进行分类。作者通过Python的sklearn库加载数据,并利用pandas、matplotlib等工具进行数据分析和可视化。
1037 70
|
机器学习/深度学习 算法 PyTorch
【从零开始学习深度学习】38. Pytorch实战案例:梯度下降、随机梯度下降、小批量随机梯度下降3种优化算法对比【含数据集与源码】
【从零开始学习深度学习】38. Pytorch实战案例:梯度下降、随机梯度下降、小批量随机梯度下降3种优化算法对比【含数据集与源码】
|
存储 算法 Java
Java数据结构与算法:用于高效地存储和检索字符串数据集
Java数据结构与算法:用于高效地存储和检索字符串数据集
|
机器学习/深度学习 分布式计算 并行计算
【机器学习】怎样在非常大的数据集上执行K-means算法?
【5月更文挑战第13天】【机器学习】怎样在非常大的数据集上执行K-means算法?
|
算法 网络协议 数据建模
【计算机网络】—— IP协议及动态路由算法(下)
【计算机网络】—— IP协议及动态路由算法(下)
264 0
|
算法 网络协议 数据建模
【计算机网络】—— IP协议及动态路由算法(上)
【计算机网络】—— IP协议及动态路由算法(上)
826 0
|
算法 搜索推荐 数据挖掘
MATLAB模糊C均值聚类FCM改进的推荐系统协同过滤算法分析MovieLens电影数据集
MATLAB模糊C均值聚类FCM改进的推荐系统协同过滤算法分析MovieLens电影数据集
|
4月前
|
机器学习/深度学习 算法 安全
【PSO-LSTM】基于PSO优化LSTM网络的电力负荷预测(Python代码实现)
【PSO-LSTM】基于PSO优化LSTM网络的电力负荷预测(Python代码实现)
264 0
|
6月前
|
机器学习/深度学习 算法 数据挖掘
基于WOA鲸鱼优化的BiLSTM双向长短期记忆网络序列预测算法matlab仿真,对比BiLSTM和LSTM
本项目基于MATLAB 2022a/2024b实现,采用WOA优化的BiLSTM算法进行序列预测。核心代码包含完整中文注释与操作视频,展示从参数优化到模型训练、预测的全流程。BiLSTM通过前向与后向LSTM结合,有效捕捉序列前后文信息,解决传统RNN梯度消失问题。WOA优化超参数(如学习率、隐藏层神经元数),提升模型性能,避免局部最优解。附有运行效果图预览,最终输出预测值与实际值对比,RMSE评估精度。适合研究时序数据分析与深度学习优化的开发者参考。