TensorFlow卷积神经网络(CNN)示例 - 高级API

Convolutional Neural Network Example - tf.layers API

CNN网络结构图示

MNIST数据库

More info: http://yann.lecun.com/exdb/mnist/


In [1]:
from __future__ import division, print_function, absolute_import

# Import MNIST data,MNIST数据集导入
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=False)

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np


Extracting /tmp/data/train-images-idx3-ubyte.gz
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz

In [2]:
# Training Parameters,超参数
learning_rate = 0.001 #学习率
num_steps = 2000 # 训练步数
batch_size = 128 # 训练数据批的大小

# Network Parameters,网络参数
num_input = 784 # MNIST数据输入 (img shape: 28*28)
num_classes = 10 # MNIST所有类别 (0-9 digits)
dropout = 0.75 # Dropout, probability to keep units = (1-p),保留神经元相应的概率为(1-p)=(1-0.75)=0.25

In [3]:
# Create the neural network,创建深度神经网络
def conv_net(x_dict, n_classes, dropout, reuse, is_training):
    
    # Define a scope for reusing the variables,确定命名空间
    with tf.variable_scope('ConvNet', reuse=reuse):
        # TF Estimator类型的输入为像素
        x = x_dict['images']

        # MNIST数据输入格式为一位向量,包含784个特征 (28*28像素)
        # 用reshape函数改变形状以匹配图像的尺寸 [高 x 宽 x 通道数]
        # 输入张量的尺度为四维: [(每一)批数据的数目, 高,宽,通道数]
        x = tf.reshape(x, shape=[-1, 28, 28, 1])

        # 卷积层,32个卷积核,尺寸为5x5
        conv1 = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)
        # 最大池化层,步长为2,无需学习任何参量
        conv1 = tf.layers.max_pooling2d(conv1, 2, 2)

        # 卷积层,64个卷积核,尺寸为3x3
        conv2 = tf.layers.conv2d(conv1, 64, 3, activation=tf.nn.relu)
        # 最大池化层,步长为2,无需学习任何参量
        conv2 = tf.layers.max_pooling2d(conv2, 2, 2)

        # 展开特征为一维向量,以输入全连接层
        fc1 = tf.contrib.layers.flatten(conv2)

        # 全连接层
        fc1 = tf.layers.dense(fc1, 1024)
        # 应用Dropout (训练时打开,测试时关闭)
        fc1 = tf.layers.dropout(fc1, rate=dropout, training=is_training)

        # 输出层,预测类别
        out = tf.layers.dense(fc1, n_classes)

    return out

In [4]:
# 确定模型功能 (参照TF Estimator模版)
def model_fn(features, labels, mode):
    
    # 构建神经网络
    # 因为dropout在训练与测试时的特性不一,我们此处为训练和测试过程创建两个独立但共享权值的计算图
    logits_train = conv_net(features, num_classes, dropout, reuse=False, is_training=True)
    logits_test = conv_net(features, num_classes, dropout, reuse=True, is_training=False)
    
    # 预测
    pred_classes = tf.argmax(logits_test, axis=1)
    pred_probas = tf.nn.softmax(logits_test)
    
    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode, predictions=pred_classes) 
        
    # 确定误差函数与优化器
    loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits_train, labels=tf.cast(labels, dtype=tf.int32)))
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
    train_op = optimizer.minimize(loss_op, global_step=tf.train.get_global_step())
    
    # 评估模型精确度
    acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)
    
    # TF Estimators需要返回EstimatorSpec
    estim_specs = tf.estimator.EstimatorSpec(
      mode=mode,
      predictions=pred_classes,
      loss=loss_op,
      train_op=train_op,
      eval_metric_ops={'accuracy': acc_op})

    return estim_specs

In [5]:
# 构建Estimator
model = tf.estimator.Estimator(model_fn)


INFO:tensorflow:Using default config.
WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpdhd6F4
INFO:tensorflow:Using config: {'_save_checkpoints_secs': 600, '_session_config': None, '_keep_checkpoint_max': 5, '_tf_random_seed': 1, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_save_checkpoints_steps': None, '_model_dir': '/tmp/tmpdhd6F4', '_save_summary_steps': 100}

In [6]:
# 确定训练输入函数
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': mnist.train.images}, y=mnist.train.labels,
    batch_size=batch_size, num_epochs=None, shuffle=True)
# 开始训练模型
model.train(input_fn, steps=num_steps)


INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Saving checkpoints for 1 into /tmp/tmpdhd6F4/model.ckpt.
INFO:tensorflow:loss = 2.39026, step = 1
INFO:tensorflow:global_step/sec: 238.314
INFO:tensorflow:loss = 0.237997, step = 101 (0.421 sec)
INFO:tensorflow:global_step/sec: 255.312
INFO:tensorflow:loss = 0.0954537, step = 201 (0.392 sec)
INFO:tensorflow:global_step/sec: 257.194
INFO:tensorflow:loss = 0.121477, step = 301 (0.389 sec)
INFO:tensorflow:global_step/sec: 255.018
INFO:tensorflow:loss = 0.0539927, step = 401 (0.392 sec)
INFO:tensorflow:global_step/sec: 254.293
INFO:tensorflow:loss = 0.0440369, step = 501 (0.393 sec)
INFO:tensorflow:global_step/sec: 256.501
INFO:tensorflow:loss = 0.0247431, step = 601 (0.390 sec)
INFO:tensorflow:global_step/sec: 252.956
INFO:tensorflow:loss = 0.0738082, step = 701 (0.395 sec)
INFO:tensorflow:global_step/sec: 253.222
INFO:tensorflow:loss = 0.134998, step = 801 (0.395 sec)
INFO:tensorflow:global_step/sec: 255.606
INFO:tensorflow:loss = 0.00438448, step = 901 (0.391 sec)
INFO:tensorflow:global_step/sec: 256.306
INFO:tensorflow:loss = 0.0471991, step = 1001 (0.390 sec)
INFO:tensorflow:global_step/sec: 255.352
INFO:tensorflow:loss = 0.0371172, step = 1101 (0.392 sec)
INFO:tensorflow:global_step/sec: 253.277
INFO:tensorflow:loss = 0.0129522, step = 1201 (0.395 sec)
INFO:tensorflow:global_step/sec: 252.49
INFO:tensorflow:loss = 0.039862, step = 1301 (0.396 sec)
INFO:tensorflow:global_step/sec: 253.902
INFO:tensorflow:loss = 0.0520571, step = 1401 (0.394 sec)
INFO:tensorflow:global_step/sec: 255.572
INFO:tensorflow:loss = 0.0307549, step = 1501 (0.392 sec)
INFO:tensorflow:global_step/sec: 254.32
INFO:tensorflow:loss = 0.0108862, step = 1601 (0.393 sec)
INFO:tensorflow:global_step/sec: 255.62
INFO:tensorflow:loss = 0.0294434, step = 1701 (0.391 sec)
INFO:tensorflow:global_step/sec: 254.349
INFO:tensorflow:loss = 0.0179781, step = 1801 (0.393 sec)
INFO:tensorflow:global_step/sec: 255.508
INFO:tensorflow:loss = 0.0375271, step = 1901 (0.391 sec)
INFO:tensorflow:Saving checkpoints for 2000 into /tmp/tmpdhd6F4/model.ckpt.
INFO:tensorflow:Loss for final step: 0.00440777.
Out[6]:
<tensorflow.python.estimator.estimator.Estimator at 0x7fb80ca55c90>

In [7]:
# 评判模型
# 确定评判用输入函数
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': mnist.test.images}, y=mnist.test.labels,
    batch_size=batch_size, shuffle=False)
model.evaluate(input_fn)


INFO:tensorflow:Starting evaluation at 2017-08-21-14:25:29
INFO:tensorflow:Restoring parameters from /tmp/tmpdhd6F4/model.ckpt-2000
INFO:tensorflow:Finished evaluation at 2017-08-21-14:25:29
INFO:tensorflow:Saving dict for global step 2000: accuracy = 0.9908, global_step = 2000, loss = 0.0382241
Out[7]:
{'accuracy': 0.99080002, 'global_step': 2000, 'loss': 0.038224086}

In [8]:
# 预测单个图像
n_images = 4
# 从数据集得到测试图像
test_images = mnist.test.images[:n_images]
# 准备输入数据
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': test_images}, shuffle=False)
# 用训练好的模型预测图片类别
preds = list(model.predict(input_fn))

# 可视化显示
for i in range(n_images):
    plt.imshow(np.reshape(test_images[i], [28, 28]), cmap='gray')
    plt.show()
    print("Model prediction:", preds[i])


INFO:tensorflow:Restoring parameters from /tmp/tmpdhd6F4/model.ckpt-2000
Model prediction: 7
Model prediction: 2
Model prediction: 1
Model prediction: 0