- RNN神经网络多用于自然语言处理,但也可以用于简单的图像分类,这里做一个小小的尝试
- 由于对RNN网络理解不够深刻,只能做一些简单的解释
代码如下
# 导入全连接层函数,也可以使用tf.layers.dense()来完成最终的分类
from tensorflow.contrib.layers import fully_connected
# 导入mnist数据
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
# 这里理解为rnn网络输出数据时候的时刻,一个数据分为28个时刻
n_steps = 28
# 每个时刻有28个特征
n_inputs = 28
# 神经元个数
n_neurons = 150
# 分类的类别,共10类
n_outputs = 10
# 学习率
learning_rate = 0.001
# 读取数据 如果数据存在,直接读取,如果数据不存在,则会自动联网下载数据
mnist = input_data.read_data_sets("MNIST_data")
# 获取测试集数据,转为(-1,28,28)的矩阵格式,用于喂给循环神经网络
X_test = mnist.test.images.reshape((-1, n_steps, n_inputs))
# 获取测试集标签
y_test = mnist.test.labels
# 占位符
X = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
y = tf.placeholder(tf.int32, [None])
#lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(num_units=n_neurons)
#multi_cell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * 3)
# 这里相当于cell的堆叠操作,首先创建多个基础的lstm的cell,然后存在列表中,喂给MultiRNNCell构建RNN神经网络
multi_cell = tf.contrib.rnn.MultiRNNCell([tf.nn.rnn_cell.BasicLSTMCell(num_units=n_neurons) for i in range(3)])
# 将构建好的神经网络和数据进行动态交互,获得输出和状态
outputs, states = tf.nn.dynamic_rnn(multi_cell, X, dtype=tf.float32)
# 选择最后一个状态用于全连接的输入
top_layer_h_state = states[-1][1]
# 这里做一个线性的计算,成为最后的分类输出值
logits = fully_connected(top_layer_h_state, n_outputs, activation_fn=None, scope="softmax")
# 这里三行调用函数获得代价值
xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y)
# xentropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)
loss = tf.reduce_mean(xentropy, name="loss")
# 这里是优化器 梯度下降 降低代价
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
training_op = optimizer.minimize(loss)
# 预测
correct = tf.nn.in_top_k(logits, y, 1)
# correct = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
# 准确率
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
# 激活全局变量
init = tf.initialize_all_variables()
n_epochs = 10
batch_size = 150
# 定义gpu运行参数 如果使用的是cpu版本,则不写
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
# 开启会话 如果使用cpu版本,不写config参数
with tf.Session(config=config) as sess:
init.run()
# 大批次10次训练
for epoch in range(n_epochs):
# 小批次,分400次训练 60000 // 150
for iteration in range(mnist.train.num_examples // batch_size):
# 调用该方法可以获得小批量的训练集
X_batch, y_batch = mnist.train.next_batch(batch_size)
# 转换x的形状适合喂给构建好的网络
X_batch = X_batch.reshape((batch_size, n_steps, n_inputs))
sess.run(training_op, feed_dict={X: X_batch, y: y_batch})
acc_train = accuracy.eval(feed_dict={X: X_batch, y: y_batch})
acc_test = accuracy.eval(feed_dict={X: X_test, y: y_test})
print("Epoch", epoch, "Train accuracy =", acc_train, "Test accuracy =", acc_test)
'''
# 运行结果
Epoch 0 Train accuracy = 0.98 Test accuracy = 0.9526
Epoch 1 Train accuracy = 0.96 Test accuracy = 0.9725
Epoch 2 Train accuracy = 0.98 Test accuracy = 0.9794
Epoch 3 Train accuracy = 0.98 Test accuracy = 0.9833
Epoch 4 Train accuracy = 0.98 Test accuracy = 0.9824
'''
转载:https://blog.csdn.net/qq872890060/article/details/101627012
查看评论