Tensor flow小案例——04简易手写数字识别

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 定义神经网络中的隐藏层
def add_layer(inputs, size_inputs, size_outputs, act_fun = None):
    Weight = tf.Variable(tf.random_normal([size_inputs, size_outputs]))
    biases = tf.Variable(tf.zeros([1, size_outputs]) + 0.1)
    Wx_plus_b = tf.matmul(inputs, Weight) + biases
    if act_fun == None:
        output = Wx_plus_b
    else:
        output = act_fun(Wx_plus_b)
    return output

# 计算正确率
def compute_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

# 引入数据
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)


# 定义输入变量
xs = tf.placeholder(tf.float32, [None, 784], name='x_in')
ys = tf.placeholder(tf.float32, [None, 10], name='y_in')

# 预测值
prediction = add_layer(xs, 784, 10, act_fun=tf.nn.softmax)

# 定义代价函数
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1]))

# 定义训练方法:梯度下降;  指定学习率:0.001(一定不要太大,否则会NAN);  训练目的:最小化loss
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)


# 初始化全部变量
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

# 迭代5,000次
for i in range(5000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
    # sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
    # 输出正确率
    if i % 50 == 0:
        print(compute_accuracy(mnist.test.images, mnist.test.labels))

sess.close()

结果:

0.1072
0.6214
0.7308
0.7728
0.7939
0.8129
0.8296
0.8383
0.8468
0.8515
0.8545
0.858
0.8628
0.8616
0.868
0.8686
0.871
0.8717
0.8752
0.8734
0.8782
0.8806
0.8787
0.8795
0.8792
0.8763
0.8838
0.8799
0.8808
0.8849
0.8826
0.8829
0.8863
0.8887
0.8888
0.8878
0.8867
0.8888
0.8901
0.8918
0.8864
0.8889
0.8905
0.8922
0.8896
0.8903
0.8905
0.8934
0.8911
0.8919
0.8924
0.8922
0.8923
0.897
0.8961
0.897
0.8952
0.8966
0.8968
0.8953
0.8981
0.8984
0.8961
0.8998
0.8977
0.8987
0.8968
0.8986
0.8978
0.9001
0.9016
0.9001
0.9015
0.8989
0.9015
0.8988
0.8978
0.9023
0.9023
0.902
0.903
0.8986
0.8971
0.9024
0.9029
0.9047
0.9058
0.9045
0.9054
0.9
0.9041
0.9059
0.9038
0.9016
0.9035
0.9041
0.9076
0.9057
0.9036
0.9058

猜你喜欢

转载自blog.csdn.net/iv__vi/article/details/82899690