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最大的不同就是存在环路. ...
随机推荐
- MySQL使用普通用户访问返回ERROR 1698 (28000): Access denied for user 'root'@'localhost'
这个问题最开始查资料都说要改密码,密码不对.其实不是这个样子都. 解决方法 修改/etc/mysql/my.cnf,添加以下内容 [mysqld] skip-grant-tables 重启mysql服 ...
- Ubuntu 16.04交换Ctrl和Caps
将Caps这个鸡肋的键位换成Ctrl的人不在少数,Ubuntu 12.04 中可以通过设置-键盘更改,新版去掉了这个功能,可以通过修改系统文件实现 方法1 在~/.xinputrc中加入:setxkb ...
- Nginx安装,操作简单
命令列表 先把所有的命令给出来了. yum -y install gcc-c++ yum -y install wget yum install -y pcre pcre-devel yum inst ...
- 【洛谷P1060 开心的金明】
题目描述 金明今天很开心,家里购置的新房就要领钥匙了,新房里有一间他自己专用的很宽敞的房间.更让他高兴的是,妈妈昨天对他说:“你的房间需要购买哪些物品,怎么布置,你说了算,只要不超过NNN元钱就行”. ...
- eclipse添加market ,maven
添加market 转载自http://blog.csdn.net/buptdavid/article/details/42423247 Eclipse Marketplace是个插件应用商店,很实用的 ...
- 枚举类 enum,结构体类 struct
1.枚举类型的值,直观易于理解,见词知意. 格式: enum 枚举类名:值类型 { 值1, 值2, 值n } 每个值默认(省略“:值类型”)以int型数据存储,从0开始. 使用格式:枚举类名 变量=枚 ...
- HTML学习笔记Day8
一.设置元素背景透明属性{background:rgba(255,255,255,0.5):} 1.元素背景透明,内容正常显示: 注:opacity:value:元素背景透明内容也透明: 2.rgba ...
- socket编程以及select、epoll、poll示例详解
socket编程socket这个词可以表示很多概念,在TCP/IP协议中“IP地址 + TCP或UDP端口号”唯一标识网络通讯中的一个进程,“IP + 端口号”就称为socket.在TCP协议中,建立 ...
- Lucene的其他搜索(三)
生成索引: package com.wp.search; import java.nio.file.Paths; import org.apache.lucene.analysis.Analyzer; ...
- 增删改查的SSM小项目
经过将近一个月的摸索,终于算是勉强完成了关于增删改查的SSM项目. github源码地址:https://github.com/123456abcdefg/Login 好了,话不多说,写一下具体代 ...