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 = 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, ])
# 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, 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.global_variables_initializer())

TF之RNN:TensorBoard可视化之基于顺序的RNN回归案例实现蓝色正弦虚线预测红色余弦实线—Jason niu的更多相关文章

  1. TF之RNN:matplotlib动态演示之基于顺序的RNN回归案例实现高效学习逐步逼近余弦曲线—Jason niu

    import tensorflow as tf import numpy as np import matplotlib.pyplot as plt BATCH_START = 0 TIME_STEP ...

  2. TF之RNN:基于顺序的RNN分类案例对手写数字图片mnist数据集实现高精度预测—Jason niu

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_dat ...

  3. TF:利用TF的train.Saver将训练好的variables(W、b)保存到指定的index、meda文件—Jason niu

    import tensorflow as tf import numpy as np W = tf.Variable([[2,1,8],[1,2,5]], dtype=tf.float32, name ...

  4. TF:利用TF的train.Saver载入曾经训练好的variables(W、b)以供预测新的数据—Jason niu

    import tensorflow as tf import numpy as np W = tf.Variable(np.arange(6).reshape((2, 3)), dtype=tf.fl ...

  5. Tensorflow学习笔记3:TensorBoard可视化学习

    TensorBoard简介 Tensorflow发布包中提供了TensorBoard,用于展示Tensorflow任务在计算过程中的Graph.定量指标图以及附加数据.大致的效果如下所示, Tenso ...

  6. 学习TensorFlow,TensorBoard可视化网络结构和参数

    在学习深度网络框架的过程中,我们发现一个问题,就是如何输出各层网络参数,用于更好地理解,调试和优化网络?针对这个问题,TensorFlow开发了一个特别有用的可视化工具包:TensorBoard,既可 ...

  7. Tensorboard可视化

    # -*- coding: utf-8 -*-"""Created on Sun Nov 5 09:29:36 2017 @author: Admin"&quo ...

  8. tensorboard可视化节点却没有显示图像的解决方法---注意路径问题加中文文件名

    问题:完成graph中的算子,并执行tf.Session后,用tensorboard可视化节点时,没有显示图像 1. tensorboard 1.10 我是将log文件存储在E盘下面的,所以直接在E盘 ...

  9. 超简单tensorflow入门优化程序&&tensorboard可视化

    程序1 任务描述: x = 3.0, y = 100.0, 运算公式 x×W+b = y,求 W和b的最优解. 使用tensorflow编程实现: #-*- coding: utf-8 -*-) im ...

随机推荐

  1. Java学习——集合框架【4】

    一.集合框架 集合框架是一个用来代表和操纵集合的统一架构.所有的集合框架都包含如下内容: 接口:是代表集合的抽象数据类型.接口允许集合独立操纵其代表的细节.在面向对象的语言,接口通常形成一个层次. 实 ...

  2. Confluence 6 考虑使用自定义 CSS

    CSS 的知识储备 如果你没有有关 CSS 的相关知识,请参考页面  CSS Resources section 中的内容.当你打算开始对 Confluence 的样式表进行修改之前,你应该对 CSS ...

  3. Logcat命令详情

    logcat是什么? Logcat 是一个命令行工具,用于转储系统消息日志,其中包括设备引发错误时的堆叠追踪以及从您的应用使用 Log类编写的消息. 格式:[adb] logcat [<opti ...

  4. error: js/dist/app.js from UglifyJs Unexpected token: name (Dom7)

    What you did I have installed Swiper as normal dependency in my Project and import it to my scripts ...

  5. IO 多路复用

    IO 多路复用 多路复用也是要用单线程来处理客户端并发,与其他模型相比多出了select这个模块. 程序不再直接问操作系统要数据,而是先发起一个select调用,select会阻塞直到其中某个sock ...

  6. extjs中store的reload事件异步问题解决

    转载自:http://blog.sina.com.cn/s/blog_8f8b7fc10100zd75.html store0.reload({params:{start:0, limit:10}}) ...

  7. unity 3D 学习笔记

    1.父对象的初始位置设,即刚开始的空对象的根节点位置应当设置成(0,0,0) 这样设置可以避免以后出现奇怪的坐标. GameObject实际上就是一些组件的容器. unity 使用公用变量原因是,在U ...

  8. Allegro PCB Design GXL (legacy) 手动更改元器件引脚的网络

    Allegro PCB Design GXL (legacy) version 16.6-2015 1.菜单:Setup > User Preferences... 2.User Prefere ...

  9. python 读取指定div的内容

    # -*- coding:utf-8 -*- from bs4 import BeautifulSoup import urllib.request import re # 如果是网址,可以用这个办法 ...

  10. angular-cli ng build 打包完成后 打开文件显示空白

    将index.html 里面的<base href="/"> 改为<base href="./"> 前面加一个 点 就好了,然后再次打包 ...