TF之LSTM:利用基于顺序的LSTM回归算法对DIY数据集sin曲线(蓝虚)预测cos(红实)(matplotlib动态演示)
TF之LSTM:利用基于顺序的LSTM回归算法对DIY数据集sin曲线(蓝虚)预测cos(红实)(matplotlib动态演示)
目录
输出结果
代码设计
输出结果
更新……
代码设计
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as pltBATCH_START = 0
TIME_STEPS = 20
BATCH_SIZE = 50
INPUT_SIZE = 1
OUTPUT_SIZE = 1
CELL_SIZE = 10
LR = 0.006
BATCH_START_TEST = 0def 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_STEPSreturn [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_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)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_inself.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_outdef 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)
相关文章
TF之RNN:matplotlib动态演示之基于顺序的RNN回归案例实现高效学习逐步逼近余弦曲线
TF之LSTM:利用基于顺序的LSTM回归算法对DIY数据集sin曲线(蓝虚)预测cos(红实)(matplotlib动态演示)相关推荐
- TF之LSTM:利用基于顺序的LSTM回归算法对DIY数据集sin曲线(蓝虚)预测cos(红实)(matplotlib动态演示)—daiding
TF之LSTM:利用基于顺序的LSTM回归算法对DIY数据集sin曲线(蓝虚)预测cos(红实)(matplotlib动态演示)-daiding 目录 输出结果 代码设计 输出结果 代码设计 impo ...
- TF之LSTM:利用基于顺序的LSTM回归算法对DIY数据集sin曲线(蓝虚)预测cos(红实)(TensorBoard可视化)
TF之LSTM:利用基于顺序的LSTM回归算法对DIY数据集sin曲线(蓝虚)预测cos(红实)(TensorBoard可视化) 目录 输出结果 代码设计 输出结果 代码设计 import tenso ...
- DL之LSTM:基于《wonderland爱丽丝梦游仙境记》小说数据集利用LSTM算法(层加深,基于keras)对单个character字符预测
DL之LSTM:基于<wonderland爱丽丝梦游仙境记>小说数据集利用LSTM算法(层加深,基于keras)对单个character字符预测 目录 基于<wonderland爱丽 ...
- DL之LSTM:基于《wonderland爱丽丝梦游仙境记》小说数据集利用LSTM算法(基于keras)对word实现预测
DL之LSTM:基于<wonderland爱丽丝梦游仙境记>小说数据集利用LSTM算法(基于keras)对word实现预测 目录 基于<wonderland爱丽丝梦游仙境记>小 ...
- TF之GD:基于tensorflow框架搭建GD算法利用Fashion-MNIST数据集实现多分类预测(92%)
TF之GD:基于tensorflow框架搭建GD算法利用Fashion-MNIST数据集实现多分类预测(92%) 目录 输出结果 实现代码 输出结果 Successfully downloaded t ...
- DL之DCGAN:基于keras框架利用深度卷积对抗网络DCGAN算法对MNIST数据集实现图像生成
DL之DCGAN:基于keras框架利用深度卷积对抗网络DCGAN算法对MNIST数据集实现图像生成 目录 基于keras框架利用深度卷积对抗网络DCGAN算法对MNIST数据集实现图像生成 设计思路 ...
- TF之NN:利用神经网络系统自动学习散点(二次函数+noise+优化修正)输出结果可视化(matplotlib动态演示)
TF之NN:利用神经网络系统自动学习散点(二次函数+noise+优化修正)输出结果可视化(matplotlib动态演示) 目录 输出结果 代码设计 输出结果 代码设计 import tensorflo ...
- 计算机树表查找算法的适用场景,利用基于R-树连续最近邻查询算法来渲染雨滴,形成了逼真的下雨天场景图...
摘要:自动驾驶领域最近的发展表明,这些车辆在不久的将来会出现在每个城市的街道上,而这些城市不会容忍交通事故的发生.为了保证安全需求,自动驾驶汽车和被使用的软件必须在尽可能多的条件下进行详尽的测试.通常 ...
- ML之LoRBaggingRF:依次利用LoR、Bagging、RF算法对泰坦尼克号数据集 (Kaggle经典案例)获救人员进行二分类预测(最全)
ML之LoR&Bagging&RF:依次利用LoR.Bagging.RF算法对泰坦尼克号数据集 (Kaggle经典案例)获救人员进行二分类预测 目录 输出结果 设计思路 核心代码 输出 ...
最新文章
- cocos creator基础-基本控件知识
- lenet pytorch 官方demo学习笔记
- 《Linux内核分析》课程总结
- Android中SlidingDrawer开发报错You need to use a Theme.AppCompat theme (or descendant) with this activity.
- yanobox nodes 3 Mac新一代点线粒子特效运动图形插件
- 洛谷 深基 第1部分 语言入门 第7章 函数与结构体
- HTTP的请求报文响应报文
- 什么是AWT_Swing_Vector?居然这么高频使用
- Win7升Windows10有获取通知,但是就不推送的解决方法
- 明细表批量新增,修改,删除sql
- 汇编proto、proc、invoke伪指令与函数声明、函数定义、函数调用
- 什么是探索性测试?探索性测试有哪些方法?
- RuntimeError: Exporting the operator var to ONNX opset version 11 is not supported. Please open a bu
- 如何利用国内开源镜像站,下载想要的资源
- python实现抠图_python和opencv实现抠图
- 基于Paddle Lite在Android手机上实现图像分类
- 两边同时取对数求复合函数_大学高等数学:第二章第四讲几类复合函数求导法,真该学习下...
- 20分钟学会TCGA数据处理的视频链接
- can总线rollingcounter_[翻译]识别 CAN 总线上的攻击
- MySql 查询数据库中所有表名