tensorflow1.0 lstm学习曲线
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt BATCH_START = 0
TIME_STEPS = 20
BATCH_SIZE = 20
INPUT_SIZE = 1
OUTPUT_SIZE = 1
CELL_SIZE = 10
LR = 0.0025 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
# plt.plot(xs[0, :], res[0, :], 'r', xs[0, :], seq[0, :], 'b--')
# plt.show()
# returned seq, res and xs: shape (batch, step, input)
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_loss()
with tf.name_scope('train'):
self.train_op = tf.train.AdamOptimizer(LR).minimize(self.loss) 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') 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) 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') def compute_loss(self):
prediction = tf.reshape(self.pred, [-1], name='reshape_pred')
ys = tf.reshape(self.ys, [-1], name='reshape_target')
self.loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[0])) @staticmethod
def ms_error(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)
sess = tf.Session()
# tf.initialize_all_variables() no long valid from
# 2017-03-02 if using tensorflow >= 0.12
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
sess.run(init)
# relocate to the local dir and run this line to view it on Chrome (http://0.0.0.0:6006/):
# $ tensorboard --logdir='logs'
plt.figure(figsize=(12, 4))
plt.ion()
plt.show()
for i in range(300):
seq, res, xs = get_batch()
if i == 0:
feed_dict = {
model.xs: seq,
model.ys: res,
# create initial state
}
else:
feed_dict = {
model.xs: seq,
model.ys: res,
model.cell_init_state: state # use last state as the initial state for this run
} _, cost, state, pred = sess.run(
[model.train_op, model.loss, model.cell_final_state, model.pred],
feed_dict=feed_dict) # plotting
plt.plot(xs[0, :], seq[0].flatten(), 'r', xs[0, :], pred.flatten()[:TIME_STEPS], 'b--')
plt.ylim((-1.5, 1.5))
plt.draw()
plt.pause(0.1) if i % 20 == 0:
print('loss: ', round(cost, 4))

tensorflow1.0 lstm学习曲线的更多相关文章
- Ubuntu14.10安装TensorFlow1.0.1
本文记录了在Ubuntu上安装TensorFlow的步骤.系统环境:Ubuntu14.10 64bitPython版本:Python 2.7.8TensorFlow版:TensorFlow 1.0.1 ...
- tensorflow1.0 构建lstm做图片分类
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #this is data mni ...
- 初用Linux, 安装Ubuntu16.04+NVIDIA387+CUDA8.0+cudnn5.1+TensorFlow1.0.1
因为最近Deep Learning十分热门, 装一下TensorFlow学习一下. 本文主要介绍安装流程, 将自己遇到的问题说明出来, 并记录自己如何处理, 原理方面并没有能力解释. 由于本人之前从来 ...
- tensorflow1.0.0 弃用了几个operator写法
除法和取模运算符(/, //, %)现已匹配 Python(flooring)语义.这也适用于 tf.div 和 tf.mod.为了获取强制的基于整数截断的行为,你可以使用 tf.truncatedi ...
- tensorflow1.0中的改善
TensorFlow 1.0 重大功能及改善 XLA(实验版):初始版本的XLA,针对TensorFlow图(graph)的专用编译器,面向CPU和GPU. TensorFlow Debugger(t ...
- tensorflow1.0 队列FIFOQueue管理实现异步读取训练
import tensorflow as tf #模拟异步子线程 存入样本, 主线程 读取样本 # 1. 定义一个队列,1000 Q = tf.FIFOQueue(1000,tf.float32) # ...
- tensorflow1.0 数据队列FIFOQueue的使用
import tensorflow as tf #模拟一下同步先处理数据,然后才能取数据训练 #tensorflow当中,运行操作有依赖性 #1.首先定义队列 Q = tf.FIFOQueue(3,t ...
- tensorflow1.0 dropout层
""" Please note, this code is only for python 3+. If you are using python 2+, please ...
- tensorflow1.0 构建卷积神经网络
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import os os.envi ...
随机推荐
- 本机安装oracle12C
1.先安装的oracle12C,创建了oracle主目录用户admin,其中主目录用户为admin,口令为123456. 2.其次创建监听,再创建数据库实例. 3.全局数据库名称为orcl.lan,管 ...
- .Net Core2.2 使用 AutoMapper进行实体转换
一.遇到的问题 在. Core Api 的编写中,我们经常会对一些功能点进行新增编辑操作,同时我们有时也会进行查询,但是我们查询的表的数据与我们返回的数据相差甚大,这是我们有需要自己手动进行类型的转换 ...
- coding++:Semaphore—RateLimiter-漏桶算法-令牌桶算法
java中对于生产者消费者模型,或者小米手机营销 1分钟卖多少台手机等都存在限流的思想在里面. 关于限流 目前存在两大类,从线程个数(jdk1.5 Semaphore)和RateLimiter速率(g ...
- ASP.NET Core单文件和多文件上传并保存到服务端
前言: 在我们日常开发中,关于图片,视频,音频,文档等相关文件上传并保存到服务端中是非常常见的一个功能,今天主要是把自己在开发中常用的两种方式记录下来方便一下直接使用,并且希望能够帮助到有需要的同学! ...
- SQL 实习
一. tem表 group by 分组后,有三个编号,找出最下的订单时间,比较选出时间段内的数据.注意group by 和 having的用法. group by 的用法 不用聚合函数的时候,每类出现 ...
- Qt实现学生学籍管理系统(文件存储)
记录 19:53 2019-07-30 在小学期学c++做完课设后萌生了把写完的课设放在博客上的想法,于是,我第一篇博客诞生了. 22:32:19 2019-07-30 下棋 16:04:56 201 ...
- Spring Taco Cloud——Controller的创建(含SpringMVC执行过程&SpringBoot&Spring三者解释及关联)
在记录这次控制器编写前,对于Spring的感觉就是经常提这样代码好简洁,这样好方便,这个是用来干嘛的诸如之类的话. What is Spring ?这是我想问自己的,一直认为是简化代码利于工程的开源框 ...
- 构建Mysql服务器
<综合>构建Mysql服务器 构建MySQL服务器 数据库基本管理 MySQL 数据类型 表结构的调整 1 构建MySQL服务器 1.1 问题 本案例要求熟悉MySQL官方安装包的使用,快 ...
- 【php】面向对象(二)
一. 封装: a) 描述:使用成员修饰符修饰成员属性和成员方法,能够最大限度的隐藏对象内部的细节,保证对象的安全 b) PPP修饰符:public(公共的),protected(受保护的),priva ...
- 按公式产生随机数、java中的重载、递归、有关计算机计算的问题
1.按公式产生随机数x1=(16807*x)%(Integer.MAX_VALUE)x=x1;通过这个公式进行随机数的产生,当产生的数字大于2e+32-2时,在用产生随机数的方式进行数字的输出.主要思 ...