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最大的不同就是存在环路. ...
随机推荐
- Nodejs nmp 常用命令
npm是一个node包管理和分发工具,已经成为了非官方的发布node模块(包)的标准.有了npm,可以很快的找到特定服务要使用的包,进行下载.安装以及管理已经安装的包. 1.npm install m ...
- JavaScript深入之变量对象
前言 在上篇<javascript深入之执行上下文栈>中讲到,当javascript代码执行一段可执行代码(executable code)时,会创建对应的执行上下文(execution ...
- (链表 双指针) leetcode 160. Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins. For ex ...
- (最小生成树) codeVs 1231 最优布线问题
题目描述 Description 学校需要将n台计算机连接起来,不同的2台计算机之间的连接费用可能是不同的.为了节省费用,我们考虑采用间接数据传输结束,就是一台计算机可以间接地通过其他计算机实现和另外 ...
- node.js(基础四)_express基础
一.前言 本次内容主要包括: 1.express的基本用法 2.express中的静 ...
- Mac 上有哪些比较有意思的小软件?
文章素材来源:微博.新浪看点 收录于:风云社区(SCOEE)[提供mac软件下载] 更多专题,可关注小编[磨人的小妖精],查看我的文章,也可上[风云社区 SCOEE],查找和下载相关软件资源. (一) ...
- 启动oracle的步骤
启动oracle的步骤 Linux下启动oracle分为以下两步: 1.1.启动lsnrctl监听. 1.2.启动数据库实例. 启动oracle监听 首先登陆服务器,切换到oracle用户. [adm ...
- linux之awk命令获取最后一列
统计分析中经常用的awk命令,其中用的最多的还是切分 cat test | awk -F',' '{print $1,$2} 能够很好的将记录按照需要切分开, 但是如何获取最后一列呢? 可以使用aw ...
- vue表单校验提交报错TypeError: Cannot read property 'validate' of undefined
TypeError: Cannot read property 'validate' of undefined at VueComponent.submitForm (plat_users.html: ...
- WEB网站类型系统中使用的OFFICE控件
WEB下使用的OFFICE控件介绍,另提供一个原创破解首先来个名词解释,Office网络文档控件,就是在网页中编辑office文档的控件(前提是browser已经安装OFFICE).最近一个项目需要用 ...