Ubuntu16.04安装TensorFlow及Mnist训练

版权声明:本文为博主原创文章,欢迎转载,并请注明出处。联系方式:460356155@qq.com

TensorFlow是Google开发的开源的深度学习框架,也是当前使用最广泛的深度学习框架。

一、安装

ubuntu16.04安装TensorFlow很简单:

pip install tensorflow==1.1.0 --user

安装是否成功验证:

>>> import tensorflow as tf

>>> tf.__version__

'1.1.0'

>>> session = tf.Session()

>>> a = tf.constant(100)

>>> b = tf.constant(200)

>>> print(session.run(a+b))

300

二、Mnist训练

定义三层全连接的网络结构:768 × 300 × 10,完整代码如下:

# -*- coding:utf-8 -*-

u"""TensorFlow训练Mnist"""

__author__ = 'zhengbiqing 460356155@qq.com'


import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


# 超参数定义
learning_rate = 0.5
epochs = 5000
batch_size = 128


def main():
    # 模型定义
    # 输入图片为28 x 28 = 784 像素
    x = tf.placeholder(tf.float32, [None, 784])

    # 输入层---->隐藏层权重及bias初始化
    W1 = tf.Variable(tf.random_normal([784, 300], stddev=0.03), name='W1')
    b1 = tf.Variable(tf.random_normal([300]), name='b1')

    # 隐藏层---->输出层权重及bias初始化
    W2 = tf.Variable(tf.random_normal([300, 10], stddev=0.03), name='W2')
    b2 = tf.Variable(tf.random_normal([10]), name='b2')


    # 隐藏层输出计算
    hidden_out = tf.add(tf.matmul(x, W1), b1)
    hidden_out = tf.nn.relu(hidden_out)


    # 模型输出
    model_out = tf.nn.softmax(tf.add(tf.matmul(hidden_out, W2), b2))
    # model_out = tf.nn.softmax(model_out)

    
    # 交叉熵定义
    y = tf.placeholder(tf.int64, [None])
    cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=y, logits=model_out)


    # 优化器,确定优化目标
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)


    # mnist 数据集
    mnist = input_data.read_data_sets("MNIST_data/")


    # 创建session
    with tf.Session() as sess:
        # session初始化
        tf.global_variables_initializer().run(session=sess)

        # 模型训练
        for epoch in range(epochs):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})

            # 测试准确率
            if epoch % 50 == 0:
                correct = tf.equal(tf.argmax(model_out, 1), y)
                accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
                acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
                print('Epoch:%d, Acc:%f' % (epoch, acc))


if __name__ == '__main__':
    main()

运行结果:

zbq@zbq:~/tf$ python tf-minist.py

Extracting MNIST_data/train-images-idx3-ubyte.gz

Extracting MNIST_data/train-labels-idx1-ubyte.gz

Extracting MNIST_data/t10k-images-idx3-ubyte.gz

Extracting MNIST_data/t10k-labels-idx1-ubyte.gz

Epoch:0, Acc:0.097400

Epoch:50, Acc:0.606300

Epoch:100, Acc:0.726400

Epoch:150, Acc:0.745900

Epoch:200, Acc:0.751400

......

Epoch:4800, Acc:0.957200

Epoch:4850, Acc:0.957800

Epoch:4900, Acc:0.958000

Epoch:4950, Acc:0.958700

运行5000个迭代,准确率达到了95%左右,对一个简单的三层全连接网络,该准确率还是不错的。