第一次用 TensorFlow

3 月份的时候其实用过一次 TF 的,但当时记忆一点都不深……而且没有硬件,跑什么东西都跑不起来。

现在 TF 出了正式版了,改动也比较大,于是就重新学 TF。

下面是一个 LeNet5 的例子,是根据 Tutorial 改的。

TensorFlow Tutorial 里面 “MNIST 高级教程” 里面是有一个 LeNet5 的例子的。跑完之后看了一下 Yan Lecun 的文章,发现好像教程和文章并不完全对应。教程中的每层的特征数更多,并且加入了 Dropout。那么就自己对着论文试着写一下这个网络吧。(反正肯定还跟作者文章中的网络不对应)

首先,输入改为了 28x28。之后,里面的特征维度按照 Lecon 的文章改了一下。

代码

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None


def deepnn(x):
    x_image = tf.reshape(x, [-1, 28, 28, 1])

    conv_1_W = weight_variable([5, 5, 1, 6])
    conv_1_b = bias_variable([6])
    conv_1 = tf.nn.relu(tf.nn.conv2d(x_image, conv_1_W, strides=[1, 1, 1, 1], padding="SAME") + conv_1_b)

    pool_2 = max_pool_2x2(conv_1)

    conv_3_W = weight_variable([5, 5, 6, 16])
    conv_3_b = bias_variable([16])
    conv_3 = tf.nn.relu(tf.nn.conv2d(pool_2, conv_3_W, strides=[1, 1, 1, 1], padding="VALID") + conv_3_b)

    pool_4 = max_pool_2x2(conv_3)

    conv_5_W = weight_variable([5, 5, 16, 120])
    conv_5_b = bias_variable([120])
    conv_5 = tf.nn.relu(tf.nn.conv2d(pool_4, conv_5_W, strides=[1, 1, 1, 1], padding="VALID") + conv_5_b)

    conv_5_reshape = tf.reshape(conv_5, [-1, 120])

    fc_6_W = weight_variable([120, 84])
    fc_6_b = bias_variable([84])
    fc_6 = tf.matmul(conv_5_reshape, fc_6_W) + fc_6_b

    output_W = weight_variable([84, 10])
    output_b = bias_variable([10])
    output = tf.matmul(fc_6, output_W) + output_b

    return output


def conv2d(x, W):
    """conv2d returns a 2d convolution layer with full stride."""
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


def max_pool_2x2(x):
    """max_pool_2x2 downsamples a feature map by 2X."""
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                          strides=[1, 2, 2, 1], padding='SAME')


def weight_variable(shape):
    """weight_variable generates a weight variable of a given shape."""
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)


def bias_variable(shape):
    """bias_variable generates a bias variable of a given shape."""
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)


def main(_):
    # 读数据
    mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
    # 设置 PlaceHolder
    x = tf.placeholder(tf.float32, [None, 784])
    y_ = tf.placeholder(tf.float32, [None, 10])
    # 构建网络
    y_conv = deepnn(x)
    # 定义 Loss
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
    # 定义如何优化
    train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)
    # 输出用的 “精度”
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    with tf.Session() as sess:
        tf.global_variables_initializer().run()
        for i in range(20000):
            data_x, data_y = mnist.train.next_batch(50)
            if i % 100 == 0:
                train_accuracy = accuracy.eval(feed_dict={x: data_x, y_: data_y})
                train_loss = loss.eval(feed_dict={x: data_x, y_: data_y})
                print('迭代次数 %d, loss %g, 精度 %g' % (i, train_loss, train_accuracy))
            train_step.run(feed_dict={x: data_x, y_: data_y})

        print('测试精度 %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--data_dir', type=str, default='data_mnist', help='数据存放位置')
    FLAGS, unparsed = parser.parse_known_args()
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

参考资料

留下评论