跟我学算法- tensorflow 实现RNN操作

对一张图片实现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.")

原文地址:https://www.cnblogs.com/my-love-is-python/p/9572001.html

时间: 2024-08-03 14:09:19

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

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

save =  tf.train.Saver() 通过save. save() 实现数据的加载 通过save.restore() 实现数据的导出 第一步: 数据的载入 import tensorflow as tf #创建变量 v1 = tf.Variable(tf.random_normal([1, 2], name='v1')) v2 = tf.Variable(tf.random_normal([2, 3], name='v2')) #初始化变量 init_op = tf.global_v

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

使用captcha.image.Image 生成随机验证码,随机生成的验证码为0到9的数字,验证码有4位数字组成,这是一个自己生成验证码,自己不断训练的模型 使用三层卷积层,三层池化层,二层全连接层来进行组合 第一步:定义生成随机验证码图片 number = ['0','1','2','3','4','5','6','7','8','9'] # alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',

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

一 初始化RNN 上一节中介绍了 通过cell类构建RNN的函数,其中有一个参数initial_state,即cell初始状态参数,TensorFlow中封装了对其初始化的方法. 1.初始化为0 对于正向或反向,第一个cell传入时没有之前的序列输出值,所以需要对其进行初始化.一般来讲,不用刻意取指定,系统会默认初始化为0,当然也可以手动指定其初始化为0. initial_state = lstm_cell.zero_state(batch_size, dtype=tf.float32) 2.初

1169: 零起点学算法76——绝对公正的裁判

1169: 零起点学算法76--绝对公正的裁判 Time Limit: 1 Sec  Memory Limit: 128 MB   64bit IO Format: %lldSubmitted: 510  Accepted: 336[Submit][Status][Web Board] Description 大家知道我们学校的OnlineJudge吗?,你知道他会告诉你什么呢? Compiling : 您提交的代码正在被编译.Running : 您的程序正在OJ上运行.Judging : OJ

1151: 零起点学算法58——开灯问题

1151: 零起点学算法58--开灯问题 Time Limit: 1 Sec  Memory Limit: 64 MB   64bit IO Format: %lldSubmitted: 3195  Accepted: 1445[Submit][Status][Web Board] Description 计算中心有8个机房,每个机房有n台电脑.每台电脑都有一个编号,比如8号机房编号就为H1到Hn,我们有时又称为H1为1号机器,H2为2号机器,.... 有一天我们学校跻身世界高校100强,全校所

PHP-密码学算法及其应用-对称密码算法

转自:http://www.smatrix.org/bbs/simple/index.php?t5662.html //////////////////////////////////////////////////////////////////////////////目录1.    PHP的散列函数及其应用2.    PHP中的对称密码算法及其应用3.    PHP的公钥密码算法及其应用/////////////////////////////////////////////////////

0基础学算法 第二弹 排序

大家好啊,这是0算法基础学算法系列第二篇,上次我在第一弹里讲了关于流程图的内容,我寻思着,这次讲些什么好呢,于是我决定,教大家一个很基础的算法,那就是排序,排序有很多方法,如果你有更多方法请在评论区里留言哦. 排序在程序中特别实用,常用的有快速排序,桶排序,冒泡排序,插入排序等等,在这里我不建议使用冒泡排序或者插入排序,建议桶排序和快速排序,这两个排序非常实用,时间复杂度低,理解起来也很容易,首先,你先思考一下,怎么用程序进行排序,然后你再来看看你的思路合理不合理,最后试着用程序实现它,实现后你

1165: 零起点学算法72——首字母变大写

1165: 零起点学算法72--首字母变大写 Time Limit: 1 Sec  Memory Limit: 64 MB   64bit IO Format: %lldSubmitted: 705  Accepted: 439[Submit][Status][Web Board] Description 输入一个英文句子,将每个单词的第一个字母改成大写字母. Input 输入数据包含多个测试实例,每个测试实例是一个长度不超过100的英文句子,占一行. Output 请输出按照要求改写后的英文句

1127: 零起点学算法34——继续求多项式

1127: 零起点学算法34--继续求多项式 Time Limit: 1 Sec  Memory Limit: 64 MB   64bit IO Format: %lldSubmitted: 3481  Accepted: 1985[Submit][Status][Web Board] Description 输入1个正整数n, 计算1+(1+2)+(1+2+3)+...+(1+2+3+...+n) Input 输入正整数n(多组数据) Output 输出1+(1+2)+(1+2+3)+...+