TensorFlow从入门到理解(四):你的第一个循环神经网络RNN(分类例子)
运行代码:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data # set random seed for comparing the two result calculations
tf.set_random_seed(1) # this is data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True) # hyperparameters
lr = 0.001
training_iters = 100000
batch_size = 128 n_inputs = 28 # MNIST data input (img shape: 28*28)
n_steps = 28 # time steps
n_hidden_units = 128 # neurons in hidden layer
n_classes = 10 # MNIST classes (0-9 digits) # tf Graph input
x = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
y = tf.placeholder(tf.float32, [None, n_classes]) # Define weights
weights = {
# (28, 128)
'in': tf.Variable(tf.random_normal([n_inputs, n_hidden_units])),
# (128, 10)
'out': tf.Variable(tf.random_normal([n_hidden_units, n_classes]))
}
biases = {
# (128, )
'in': tf.Variable(tf.constant(0.1, shape=[n_hidden_units, ])),
# (10, )
'out': tf.Variable(tf.constant(0.1, shape=[n_classes, ]))
} def RNN(X, weights, biases):
# hidden layer for input to cell # transpose the inputs shape from
# X ==> (128 batch * 28 steps, 28 inputs)
X = tf.reshape(X, [-1, n_inputs]) # into hidden
# X_in = (128 batch * 28 steps, 128 hidden)
X_in = tf.matmul(X, weights['in']) + biases['in']
# X_in ==> (128 batch, 28 steps, 128 hidden)
X_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units]) # cell
########################################## # basic LSTM Cell.
cell = tf.contrib.rnn.BasicLSTMCell(n_hidden_units)
# lstm cell is divided into two parts (c_state, h_state)
init_state = cell.zero_state(batch_size, dtype=tf.float32) outputs, final_state = tf.nn.dynamic_rnn(cell, X_in, initial_state=init_state, time_major=False) # unpack to list [(batch, outputs)..] * steps
outputs = tf.unstack(tf.transpose(outputs, [1,0,2]))
results = tf.matmul(outputs[-1], weights['out']) + biases['out'] # shape = (128, 10) return results pred = RNN(x, weights, biases)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
train_op = tf.train.AdamOptimizer(lr).minimize(cost) correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
step = 0
while step * batch_size < training_iters:
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
batch_xs = batch_xs.reshape([batch_size, n_steps, n_inputs])
sess.run([train_op], feed_dict={
x: batch_xs,
y: batch_ys,
})
if step % 20 == 0:
print(sess.run(accuracy, feed_dict={
x: batch_xs,
y: batch_ys,
}))
step += 1
运行结果:

TensorFlow从入门到理解(四):你的第一个循环神经网络RNN(分类例子)的更多相关文章
- TensorFlow从入门到理解(五):你的第一个循环神经网络RNN(回归例子)
运行代码: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt BATCH_START = 0 TIM ...
- TensorFlow从入门到理解
一.<莫烦Python>学习笔记: TensorFlow从入门到理解(一):搭建开发环境[基于Ubuntu18.04] TensorFlow从入门到理解(二):你的第一个神经网络 Tens ...
- 通过keras例子理解LSTM 循环神经网络(RNN)
博文的翻译和实践: Understanding Stateful LSTM Recurrent Neural Networks in Python with Keras 正文 一个强大而流行的循环神经 ...
- 基于TensorFlow的循环神经网络(RNN)
RNN适用场景 循环神经网络(Recurrent Neural Network)适合处理和预测时序数据 RNN的特点 RNN的隐藏层之间的节点是有连接的,他的输入是输入层的输出向量.extend(上一 ...
- TensorFlow从入门到理解(六):可视化梯度下降
运行代码: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.m ...
- TensorFlow从入门到理解(三):你的第一个卷积神经网络(CNN)
运行代码: from __future__ import print_function import tensorflow as tf from tensorflow.examples.tutoria ...
- TensorFlow从入门到理解(二):你的第一个神经网络
运行代码: from __future__ import print_function import tensorflow as tf import numpy as np import matplo ...
- TensorFlow从入门到理解(一):搭建开发环境【基于Ubuntu18.04】
*注:教程及本文章皆使用Python3+语言,执行.py文件都是用终端(如果使用Python2+和IDE都会和本文描述有点不符) 一.安装,测试,卸载 TensorFlow官网介绍得很全面,很完美了, ...
- 循环神经网络-RNN入门
首先学习RNN需要一定的基础,即熟悉普通的前馈神经网络,特别是BP神经网络,最好能够手推. 所谓前馈,并不是说信号不能反向传递,而是网络在拓扑结构上不存在回路和环路. 而RNN最大的不同就是存在环路. ...
随机推荐
- luoguP4707 重返现世
收集邮票加强版,每个邮票不是等概率获得的了. 而且是获得K个,如果把一个全集S集合找出其获得时间集合(显然获得时间两两不同)的话,那么就是第n-k+1大的期望! %%%Sooke min-max容斥扩 ...
- 【洛谷P2704】炮兵阵地
题目大意:定义一个炮兵会影响该点所在坐标上下左右两个格子的范围,求一个 N*M 的网格里最多可以放多少个炮兵. 题解:发现这个问题有需要记录两个状态,即:上一层的状态和上两层的状态,若直接进行记录,空 ...
- ANIS与UNICODE字符格式转换:MultiByteToWideChar() 和WideCharToMultiByte() 函数
资料来自: http://blog.csdn.net/holamirai/article/details/47948745 http://www.cnblogs.com/wanghao111/arch ...
- Java programming problems
1.使用循环把26个字母按字典顺序存入数组,在不使用另外数组的情况下将其逆序存放,在根据处理后的字符数组创建一个字符串并输出 public static void main(String[] args ...
- Java多线程-详细版
基本概念解释 并发:一个处理器处理多个任务,这些任务对于处理器来说是交替运行的,每个时间点只有一个任务在进行. 并行:多个处理器处理多个任务,这些任务是同时运行的.每个时间点有多个任务同时进行. 进程 ...
- Unity 后处理堆
Unity安装后处理的过程:windows---PacageManager---Post Processing Post Processing后处理堆需要知道要修改那个相机渲染的内容,先定位到相机,再 ...
- nginx buffered to a temporary 解决
今天开启了nginx的error_log,发现了三个配置问题: 问题一: 2011/07/18 17:04:37 [warn] 2422#0: *171505004 an upstream respo ...
- SSH框架下ajax调用action并生成JSON再传递到客户端【以get和post方式提交】
需要完成的任务: 主要是把JSP页面上图片ID传给服务器端,服务器读取cookie看是否有username,如果有则根据ID读取MongoDB数据库,读出图片URL,再存放到mysql中的collec ...
- java连接数据库报了ssl连接的警告
警告内容:Establishing SSL connection without server's identity verification is not recommended(不建议在没有服务器 ...
- 非root用户ssh 执行 sudo远程机器免密钥
非root用户ssh 执行 sudo远程机器免密钥 # 1.登陆192.168.1.10 ssh-keygen -t rsa # 一路回车 # 将公钥添加到认证文件中 cat ~/.ssh/id_rs ...