您当前的位置:首页 > IT编程 > 深度学习
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch |

自学教程:使用RNN进行图像分类

51自学网 2020-11-24 12:26:33
  深度学习
这篇教程使用RNN进行图像分类写得很实用,希望能帮到您。

使用RNN进行图像分类

使用CNN进行图像分类是很稀疏平常的,其实使用RNN也是可以的.
这篇介绍的就是使用RNN(LSTM/GRU)进行mnist的分类,对RNN不太了解的可以看看下面的材料:
1. [LSTM的介绍] http://colah.github.io/posts/2015-08-Understanding-LSTMs/
2. [The Unreasonable Effectiveness of RNNs] http://karpathy.github.io/2015/05/21/rnn-effectiveness/
3. [WildML RNN介绍] http://www.wildml.com/2015/09/recurrent-neural-networks-tutorial-part-1-introduction-to-rnns/
4. [RNN in Tensorflow] http://www.wildml.com/2016/08/rnns-in-tensorflow-a-practical-guide-and-undocumented-features/


基础介绍

如何使用RNN进行mnist的分类呢?其实对应到RNN里面就是个Sequence Classification问题.
先看下CS231n中关于RNN部分的一张图:

rnn_cell

其实图像的分类对应上图就是个many to one的问题. 对于mnist来说其图像的size是28*28,如果将其看成28个step,每个step的size是28的话,是不是刚好符合上图. 当我们得到最终的输出的时候将其做一次线性变换就可以加softmax来分类了,其实挺简单的.

具体实现

tf中RNN有很多的变体,最出名也是最常用的就是: LSTMGRU,其它的还有向GridLSTMAttentionCell等,要查看最新tf支持的RNN类型,基本只要关注这两个文件就可以了:
1. [rnn_cell.py] https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn_cell.py
2. [contrib/rnn_cell.py] https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/rnn/python/ops/rnn_cell.py

对于常见的RNN cell的使用总结:

rnn_cell_in_tf

获取数据

很简单,tf自带都帮我们写好了,直接调用就行了.

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist_data = input_data.read_data_sets('data/mnist', one_hot=True)
  • 1
  • 2
  • 3

如何不存在data/mnist这个目录,其会自己下载mnist数据,要是你的网络不行也可以自己去mnist的网站下载然后将数据放在目录下就可以了.

tf贴心到什么程度呢?连batch generator都帮我们写好了,直接用next_batch就可以获得下一个batch的数据.

train_x, train_y = mnist_data.train.images, mnist_data.train.labels
test_x, test_y = mnist_data.test.images, mnist_data.test.labels
batch_x, batch_y = mnist.train.next_batch(batch_size)
  • 1
  • 2
  • 3

training examples是55000, test examples是10000,validation examples是5000.

定义网络

我们使用3层的GRUhidden units是200的带dropout的RNN来作为mnist分类的网络,具体代码如下:

cells = list()
for _ in range(num_layers):
    cell = tf.nn.rnn_cell.GRUCell(num_units=num_hidden)
    cell = tf.nn.rnn_cell.DropoutWrapper(cell=cell, output_keep_prob=1.0-dropout)
    cells.append(cell)
network = tf.nn.rnn_cell.MultiRNNCell(cells=cells)
outputs, last_state = tf.nn.dynamic_rnn(cell=network, inputs=data, dtype=tf.float32)

# get last output
outputs = tf.transpose(outputs, (1, 0, 2))
last_output = tf.gather(outputs, int(outputs.get_shape()[0])-1)

# linear transform
out_size = int(target.get_shape()[1])
weight, bias = initialize_weight_bias(in_size=num_hidden, out_size=out_size)
logits = tf.add(tf.matmul(last_output, weight), bias)

return logits
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

因为mnist太简单,这个简单的网络其实已经可以搞定mnist的分类问题,后期的test acc可以到0.985(within 3 epoches).

训练和测试

分类嘛,还是使用cross entropy作为loss,然后计算下错误率是多少,代码如下:
batch_size = 64, lr = 0.001

# placeholders
input_x = tf.placeholder(tf.float32, shape=(None, 28, 28))
input_y = tf.placeholder(tf.float32, shape=(None, 10))
dropout = tf.placeholder(tf.float32)
input_logits = model(input_x, input_y, dropout)

# loss and error rate op
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=input_logits, labels=input_y))
train_op = tf.train.RMSPropOptimizer(0.001).minimize(loss)
input_prob = tf.nn.softmax(input_logits)
error_count = tf.not_equal(tf.arg_max(input_prob, 1), tf.arg_max(input_y, 1))
error_rate_op = tf.reduce_mean(tf.cast(error_count, tf.float32))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

input_xinput_y表示输入的image和label,model就是上面定义的3层GRU模型;可以使用tf.summary来使用tensorboard查看训练时的error rateloss等信息.

训练代码:

for step in range(total_steps):
    train_x, train_y = mnist_data.train.next_batch(default_batch_size)
    train_x = train_x.reshape(-1, 28, 28)
    feed_dict = {input_x: train_x,
                 input_y: train_y,
                 dropout: default_dropout}
    _, summary = session.run([train_op, merge_summary_op], feed_dict=feed_dict)
    # write logs
  summary_writer.add_summary(summary, global_step=epoch*total_steps+step)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

测试代码:

# test
if step > 0 and (step % test_freq == 0):
    avg_error = 0
    for test_step in range(total_test_steps):
        test_x, test_y = mnist_data.test.next_batch(default_batch_size)
        test_x = test_x.reshape(-1, 28, 28)
        feed_dict = {input_x: test_x,
                     input_y: test_y,
                     dropout: 0}
        test_error = session.run(error_rate_op, feed_dict=feed_dict)
        avg_error += test_error / total_test_steps
    print('epoch: %d, steps: %d, avg_test_error: %.4f' % (epoch, step, avg_error))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

结果

训练时的loss和error_rate:

train_loss

测试的error_rate:

test_error

我只跑了3个epoch,错误率基本降低到1.5%左右,亦即正确率在98.5%左右,多跑几个epoch可能错误率还能继续降低,不过对于我们这个demo来说已经够了.


本地MNIST数据集读取(最清晰、最实用)代码
Keras中CNN联合LSTM进行分类
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1