对一张图片实现rnn操作,主要是通过先得到一个整体,然后进行切分,得到的最后input结果输出*_w[‘out’] + _b['out']  = 最终输出结果

第一步: 数据载入

import tensorflow as tf
from tensorflow.contrib import rnn
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import matplotlib.pyplot as plt print("Packages imported") mnist = input_data.read_data_sets("data/", one_hot=True)
trainimgs, trainlabels, testimgs, testlabels \
= mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
ntrain, ntest, dim, nclasses \
= trainimgs.shape[0], testimgs.shape[0], trainimgs.shape[1], trainlabels.shape[1]

第二步: 初始化参数

diminput = 28
dimhidden = 128
# nclasses = 10
dimoutput = nclasses
nsteps = 28 # w参数初始化
weights = {
'hidden': tf.Variable(tf.random_normal([diminput, dimhidden])),
'out': tf.Variable(tf.random_normal([dimhidden, dimoutput]))
}
# b参数初始化
biases = {
'hidden': tf.Variable(tf.random_normal([dimhidden])),
'out': tf.Variable(tf.random_normal([dimoutput]))
}

第三步: 构建RNN函数

def _RNN(_X, _W, _b, _nsteps, _name):
# 第一步:转换输入,输入_X是还有batchSize=5的5张28*28图片,需要将输入从
# [batchSize,nsteps,diminput]==>[nsteps,batchSize,diminput]
_X = tf.transpose(_X, [1, 0, 2])
# 第二步:reshape _X为[nsteps*batchSize,diminput]
_X = tf.reshape(_X, [-1, diminput])
# 第三步:input layer -> hidden layer
_H = tf.matmul(_X, _W['hidden']) + _b['hidden']
# 第四步:将数据切分为‘nsteps’个切片,第i个切片为第i个batch data
# tensoflow >0.12
_Hsplit = tf.split(_H, _nsteps, 0)
# tensoflow <0.12 _Hsplit = tf.split(0,_nsteps,_H)
# 第五步:计算LSTM final output(_LSTM_O) 和 state(_LSTM_S)
# _LSTM_O和_LSTM_S都有‘batchSize’个元素
# _LSTM_O用于预测输出
with tf.variable_scope(_name) as scope:
# 表示公用一份变量
scope.reuse_variables()
# forget_bias = 1.0不忘记数据
###tensorflow <1.0
# lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(dimhidden,forget_bias = 1.0)
# _LSTM_O,_SLTM_S = tf.nn.rnn(lstm_cell,_Hsplit,dtype=tf.float32)
###tensorflow 1.0
lstm_cell = rnn.BasicLSTMCell(dimhidden)
_LSTM_O, _LSTM_S = rnn.static_rnn(lstm_cell, _Hsplit, dtype=tf.float32)
# 第六步:输出,需要最后一个RNN单元作为预测输出所以取_LSTM_O[-1]
_O = tf.matmul(_LSTM_O[-1], _W['out']) + _b['out']
return {
'X': _X,
'H': _H,
'_Hsplit': _Hsplit,
'LSTM_O': _LSTM_O,
'LSTM_S': _LSTM_S,
'O': _O
}

第四步: 构建cost函数和准确度函数

learning_rate = 0.001
x = tf.placeholder("float", [None, nsteps, diminput])
y = tf.placeholder("float", [None, dimoutput])
myrnn = _RNN(x, weights, biases, nsteps, 'basic')
pred = myrnn['O']
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) # Adam
accr = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)), tf.float32))
init = tf.global_variables_initializer()
print("Network Ready!")

第五步: 训练模型, 降低cost值,优化参数

# 训练次数
training_epochs = 5
# 每次训练的图片数
batch_size = 16
# 循环的展示次数
display_step = 1
sess = tf.Session()
sess.run(init)
print("Start optimization")
for epoch in range(training_epochs):
avg_cost = 0.
# total_batch = int(mnist.train.num_examples/batch_size)
total_batch = 100
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
batch_xs = batch_xs.reshape((batch_size, nsteps, diminput))
# print(batch_xs.shape)
# print(batch_ys.shape)
# batch_ys = batch_ys.reshape((batch_size, dimoutput))
# Fit training using batch data
feeds = {x: batch_xs, y: batch_ys}
sess.run(optm, feed_dict=feeds)
# Compute average loss
avg_cost += sess.run(cost, feed_dict=feeds) / total_batch
# Display logs per epoch step
if epoch % display_step == 0:
print("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))
feeds = {x: batch_xs, y: batch_ys}
train_acc = sess.run(accr, feed_dict=feeds)
print(" Training accuracy: %.3f" % (train_acc))
testimgs = testimgs.reshape((ntest, nsteps, diminput))
feeds = {x: testimgs, y: testlabels}
test_acc = sess.run(accr, feed_dict=feeds)
print(" Test accuracy: %.3f" % (test_acc))
print("Optimization Finished.")

跟我学算法- tensorflow 实现RNN操作的更多相关文章

  1. 跟我学算法- tensorflow VGG模型进行测试

    我们使用的VGG模型是别人已经训练好的一个19层的参数所做的一个模型 第一步:定义卷积分部操作函数 mport scipy.io import numpy as np import os import ...

  2. 跟我学算法-tensorflow 实现卷积神经网络附带保存和读取

    这里的话就不多说明了,因为上上一个博客已经说明了 import numpy as np import tensorflow as tf import matplotlib.pyplot as plt ...

  3. 跟我学算法-tensorflow 实现卷积神经网络

    我们采用的卷积神经网络是两层卷积层,两层池化层和两层全连接层 我们使用的数据是mnist数据,数据训练集的数据是50000*28*28*1 因为是黑白照片,所以通道数是1 第一次卷积采用64个filt ...

  4. 跟我学算法-tensorflow 实现线性拟合

    TensorFlow™ 是一个开放源代码软件库,用于进行高性能数值计算.借助其灵活的架构,用户可以轻松地将计算工作部署到多种平台(CPU.GPU.TPU)和设备(桌面设备.服务器集群.移动设备.边缘设 ...

  5. 跟我学算法- tensorflow 卷积神经网络训练验证码

    使用captcha.image.Image 生成随机验证码,随机生成的验证码为0到9的数字,验证码有4位数字组成,这是一个自己生成验证码,自己不断训练的模型 使用三层卷积层,三层池化层,二层全连接层来 ...

  6. 跟我学算法- tensorflow模型的保存与读取 tf.train.Saver()

    save =  tf.train.Saver() 通过save. save() 实现数据的加载 通过save.restore() 实现数据的导出 第一步: 数据的载入 import tensorflo ...

  7. 跟我学算法-tensorflow 实现神经网络

    神经网络主要是存在一个前向传播的过程,我们的目的也是使得代价函数值最小化 采用的数据是minist数据,训练集为50000*28*28 测试集为10000*28*28 lable 为50000*10, ...

  8. 跟我学算法-tensorflow 实现logistics 回归

    tensorflow每个变量封装了一个程序,需要通过sess.run 进行调用 接下来我们使用一下使用mnist数据,这是一个手写图像的数据,训练集是55000*28*28, 测试集10000* 28 ...

  9. 第二十二节,TensorFlow中RNN实现一些其它知识补充

    一 初始化RNN 上一节中介绍了 通过cell类构建RNN的函数,其中有一个参数initial_state,即cell初始状态参数,TensorFlow中封装了对其初始化的方法. 1.初始化为0 对于 ...

随机推荐

  1. Qt Creator下应用CMake项目调试mex文件

    网上可以找到很多应用Visual Studio编写.编译mex文件,并与MATLAB联合调试的文章.但这只限于Win平台,网上许多源码都是.mexa64的文件,它们的作者是怎么调试的呢?这里我介绍一下 ...

  2. html中用变量作为django字典的键值

    若字典为dic={'name': Barbie, 'age': 20},则在html中dic.name为Barbie,dic.age为20. 但若字典为dic={'Barbie': 1, 'Roger ...

  3. Kaggle比赛冠军经验分享:如何用 RNN 预测维基百科网络流量

    Kaggle比赛冠军经验分享:如何用 RNN 预测维基百科网络流量 from:https://www.leiphone.com/news/201712/zbX22Ye5wD6CiwCJ.html 导语 ...

  4. module.exports和exports

    require 用来加载代码,而 exports 和 module.exports 则用来导出代码.但很多新手可能会迷惑于 exports 和 module.exports 的区别,为了更好的理解 e ...

  5. 【hive】count() count(if) count(distinct if) sum(if)的区别

    表名: user_active_day (用户日活表) 表内容: user_id(用户id)   user_is_new(是否新用户 1:新增用户 0:老用户) location_city(用户所在地 ...

  6. FZU 2169 shadow spfa

    题目链接:shadow 好佩服自己耶~~~好厉害~~~ 麻麻再也不用担心我的spfa 和 邻接表技能了~~~ spfa 记录最短路径. #include <stdio.h> #includ ...

  7. 导入arr包

    提起项目的aar包 导入目标项目中 添加依赖 

  8. IE8下的typeof(console.log)为"object"的BUG

    今天发现IE8在开启过控制台后,console.log虽然可用,也是确实是一个函数,但是对其执行typeof操作返回的确是"object" 原生IE8:

  9. php session目录找不到的错误 Error session_start(): open(/var/lib/php/session error

    问题来源 今天安装一个应用,发现提示 Error session_start(): open(/var/lib/php/session error,估计是找不到写不了啥啥啥. 于是我就去该路径下去看看 ...

  10. nginx 配置 getsimplecms 配置文件

    getsimplecms的安装需要两个php类库,一个是dom操作,一个是gd library. 所以先安装这两个类库,重启php解释器. yum install php-xml; yum insta ...