Classification - 以 mnist 为例

以 mnist 手写数字识别为例,讲解tensorflow的分类

# 去掉 warning
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import tensorflow as tf 

# 去掉 warning
old_v = tf.logging.get_verbosity()
tf.logging.set_verbosity(tf.logging.ERROR)

# 引入 input_data 文件,这个文件用于去mnist页面获取mnist数据
from tensorflow.examples.tutorials.mnist import input_data

# 读取 mnist 数据集
mnist = input_data.read_data_sets('E:\mnist', one_hot = True)

# 定义全连接层
def add_layer(inputs, in_size, out_size, activation_function = None):
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
    if activation_function == None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

# 计算精确度
def computer_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict = {xs: v_xs})
    correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict = {xs: v_xs, ys: v_ys})
    return result

# 搭建网络
xs = tf.placeholder(tf.float32, [None, 784]) # 28*28
ys = tf.placeholder(tf.float32, [None, 10])

# 调用 add_layer 搭建一个最简单的训练神经网络,只有输入层和输出层
prediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)


# 损失函数使用交叉熵损失函数 cross_entropy
cross_entropy = tf.reduce_mean(- tf.reduce_sum(ys * tf.log(prediction), reduction_indices = [1]))

# 使用梯度下降法进行训练
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

# 全局变量初始化
init = tf.global_variables_initializer()

# 开始训练
with tf.Session() as sess:
    sess.run(init)
    for i in range(1001):
        batch_xs, batch_ys = mnist.train.next_batch(100) # 小批量梯度下降
        sess.run(train_step, feed_dict = {xs: batch_xs, ys: batch_ys})
        if i % 50 == 0:
            print('%4d: %6.4f' %(i, computer_accuracy(mnist.test.images, mnist.test.labels)))
Classification - 以 mnist 为例_第1张图片

参考资料

  • Classification
  • python输出对齐

你可能感兴趣的:(Classification - 以 mnist 为例)