用RNN加attention做手写数字识别

关于RNN部分的介绍可以看这里:https://blog.csdn.net/zgj_gutou/article/details/86501084

关于attention,其实网上的介绍原理和相关论文有很多很多,比我讲的应该会好一些。我这里再用自己的话简单通俗地解释一下,RNN+attention中,首先RNN的每个单元都会有一个输出,假设RNN的时间长度为10,也就是会有10个输出,我们利用attention去判断哪个输出是相对重要的,也就是我们需要去计算一个关于10个输出的权重向量,这个向量长度为10,向量的每个位置分别对应10个输出,我们会对10个输出和它们对应的权重进行相乘得到一个最终结果。显然,这个结果体现出了比较重要的输出,因为比较重要的输出权重比较大。所以attention的关键就是如何去计算权重大小,计算权重大小在不同的场合也有不同的方法。

下面的程序中的权重大小计算公式如下,其中的ht就是RNN单元的输出:
u t = tanh ⁡ ( W w h t + b w ) u_{t}=\tanh \left(W_{w} h_{t}+b_{w}\right) ut=tanh(Wwht+bw)
attention部分的参考博客(程序中attention部分的代码也是参考该博客的):https://blog.csdn.net/thriving_fcl/article/details/73381217 感谢!

稍微说一下attention中维度变化,因为初学者总是对维度有所疑惑,我自己也是比较注意,一旦维度错了,基本上就是报错。(下面说的变量名都是程序中的变量,像list,attention这种不是变量名)
在attention之前的,outputs是[batch_size, max_time(即n_steps), cell.output_size(即n_hidden_units)],即(256,28,128),我们通过tf.transpose函数调换了第一维和第二维的位置,并且进行了tf.unstack操作(按行分解),得到的是一个有28个维度为(256,128)的元素的list。我们在计算attention的时候,n_hidden_units作为中间变量在计算过程中去掉了,引入了一个attention_size的变量,通过计算公式得到u_list是一个有28个维度为(256,50)的元素的list,再计算一次得到的attn_z是一个有28个维度为(256,1)的list(这次线性变换是为了改变维度大小用的,去掉了50这个数,变成了1),把attn_z进行concat以后,得到的attn_zconcat维度是(256,28),再将attn_zconcat进行softmax,得到的alpha的维度是(256,28),别忘了其中的256就是batch_size,所以alpha的含义就是总共256个样本(图片),每一行表示一个样本在每个时间点的输出的权重。因为alpha后面要和outputs进行reduce_sum操作,所以alpha要进行维度的调换和变形得到alpha_trans的维度是(28,256,1)。alpha_trans和outputs进行reduce_sum之后得到的results维度是(256,128),最后以128为中间变量,引入类别数n_classes,得到一个final_output,维度为(256,10)。最后就可以跟正确的类别标签进行计算交叉熵了。
上面可能说得有点乱,可以一边看程序一边看上面的解释。

对于softmax和reduce_sum中维度变化不太明白的可以看这里:https://blog.csdn.net/zgj_gutou/article/details/86558899

完整的代码如下,可以直接复制到编译器上运行,可以把用attention的输出结果和不用attention的输出结果对比一下:
# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
This code is a modified version of the code from this link:
https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/recurrent_network.py
His code is a very good one for RNN beginners. Feel free to check it out.
"""
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
batch_size = 256

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)
attention_size = 50

# 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):
    # transpose the inputs shape from
    # X ==> (256 batch * 28 steps, 28 inputs)
    X = tf.reshape(X, [-1, n_inputs])

    # into hidden
    # X_in = (256 batch * 28 steps, 128 hidden)
    X_in = tf.matmul(X, weights['in']) + biases['in']   # 这里的维度是(256*28,128),输入先经过一个线性变化
    # X_in ==> (256 batch, 28 steps, 128 hidden)
    X_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units])   # 这里的维度是(256,28,128)

    # cell
    cell = tf.contrib.rnn.BasicLSTMCell(n_hidden_units)  # 一个lstm单元的输入是向量,所以有这么多隐藏单元n_hidden_units
    # lstm cell is divided into two parts (c_state, h_state)
    init_state = cell.zero_state(batch_size, dtype=tf.float32)   # 初始状态的维度跟batch_size和隐藏单元个数有关,这里shape=(256, 128)

    outputs, final_state = tf.nn.dynamic_rnn(cell, X_in, initial_state=init_state, time_major=False)

    # unpack to list [(batch, outputs)..] * steps
    # 这里的outputs是[batch_size, max_time, cell.output_size(即hidden_units)]的形式,现在要取最后一个时间的outputs,所以要调换一下max_time和batch_size,这样就可以直接用outputs[-1]来得到最后一个的输出
    outputs = tf.unstack(tf.transpose(outputs, [1,0,2]))  # tf.unstack默认是按行分解。
    print("outputs:",outputs)

    attention_w = tf.Variable(tf.truncated_normal([n_hidden_units, attention_size], stddev=0.1), name='attention_w')
    attention_b = tf.Variable(tf.constant(0.1, shape=[attention_size]), name='attention_b')
    u_list = []
    for t in range(n_steps):
        u_t = tf.tanh(tf.matmul(outputs[t], attention_w) + attention_b)  # u_t的shape=(256,50),output[t]表示每个时间的输出,如output[-1]表示最后一个时间的输出
        u_list.append(u_t)  # 这个u_list包含了n_steps个元素,每个元素的shape都是(256,50)
    print("u_list:",u_list)
    u_w = tf.Variable(tf.truncated_normal([attention_size, 1], stddev=0.1), name='attention_uw')
    attn_z = []
    for t in range(n_steps):
        z_t = tf.matmul(u_list[t], u_w)  # z_t的shape=(256,1),这一步线性变换其实是为了改变维度大小用的,去掉了50这个数,变成了1
        attn_z.append(z_t)   # 这个attn_z包含了28个元素,每个元素的shape都是(256, 1)
    # transform to batch_size * sequence_length
    print("attn_z:",attn_z)
    attn_zconcat = tf.concat(attn_z, axis=1)   # shape=(256,28),256是batch_size,表示样本数量
    print("attn_zconcat:",attn_zconcat)
    alpha = tf.nn.softmax(attn_zconcat)   # 得到各个权重(小数)
    # transform to sequence_length * batch_size * 1 , same rank as outputs
    alpha_trans = tf.reshape(tf.transpose(alpha, [1, 0]), [n_steps, -1, 1])  # (28,256,1)
    print("alpha_trans:",alpha_trans)
    print("outputs:",outputs)
    results = tf.reduce_sum(outputs * alpha_trans, 0)  # results的shape=(256,128)
    print("results:",results)

    fc_w = tf.Variable(tf.truncated_normal([n_hidden_units, n_classes], stddev=0.1), name='fc_w')
    fc_b = tf.Variable(tf.zeros([n_classes]), name='fc_b')
    final_output =  tf.matmul(results, fc_w) + fc_b  # shape=(256,10)

    return final_output

pred = RNN(x, weights, biases)  # 此时x还没有数值,后面用feed_dict输入
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))  # 此时y还没有数值,后面用feed_dict输入
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)
        # print(len(batch_xs))
        # print(len(batch_xs[0]))
        batch_xs = batch_xs.reshape([batch_size, n_steps, n_inputs])  # 把[batch_size,784]变形为[batch_size,28,28],这样才符合x的维度
        sess.run(train_op, feed_dict={x: batch_xs,y: batch_ys,})
        if step % 20 == 0:
            batch_xs, batch_ys = mnist.test.next_batch(batch_size)
            # 取batch_size大小的测试集,因为初始状态跟batch_size有关,所以这里取batch_size大小的测试集数据,否则会报错。也可以把batch_size作为一个参数来传递
            batch_xs = batch_xs.reshape([batch_size, n_steps, n_inputs])
            print("time:",step," accuracy:",sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys,}))
        step += 1

输出结果:

time: 0  accuracy: 0.16796875
time: 20  accuracy: 0.6640625
time: 40  accuracy: 0.76171875
time: 60  accuracy: 0.8828125
time: 80  accuracy: 0.87890625
time: 100  accuracy: 0.94140625
time: 120  accuracy: 0.90625
time: 140  accuracy: 0.93359375
time: 160  accuracy: 0.96484375
time: 180  accuracy: 0.96484375
time: 200  accuracy: 0.94921875
time: 220  accuracy: 0.94140625
time: 240  accuracy: 0.96875
time: 260  accuracy: 0.96484375
time: 280  accuracy: 0.9609375
time: 300  accuracy: 0.96484375
time: 320  accuracy: 0.97265625
time: 340  accuracy: 0.9375
time: 360  accuracy: 0.9765625
time: 380  accuracy: 0.953125
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值