Tensorflow MNIST手写数字识别简单例子

版权声明:潘广宇博客, https://blog.csdn.net/panguangyuu/article/details/87558417
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data

# 下载并载入MNIST数据集
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)

# 定义每次处理图片的块大小
batch_size = 100

# 计算共需计算多少个批次
n_batch = mnist.train.num_examples // batch_size

# 定义神经网络:占位符
x = tf.placeholder(tf.float32, [None, 784])  # None的值取决于batch_size,784是由于图片的大小为28*28
y = tf.placeholder(tf.float32, [None, 10])   # 10是因为识别0-9,10个数字

# 创建一层神经网络
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x, W) + b)

# 二次代价函数
loss = tf.reduce_mean(tf.square(y - prediction))

# 梯度下降优化器
train = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

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

# 比对真实值与预测值是否正确,返回一个bool的矩阵
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))

# 求准确率,tf.cast()将bool转化为数字,true为1.0 false为0
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# 定义会话执行
with tf.Session() as sess:
    sess.run(init)
    
    # 迭代训练21次 
    for _ in range(21):
        
        # 分批次进行训练
        for batch in range(n_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            sess.run(train, feed_dict={x:batch_x, y:batch_y})
        
        # 查看每一轮迭代的准确率
        accuracy = sess.run(acc, feed_dict={x:mnist.test.images, y:mnist.test.labels})

猜你喜欢

转载自blog.csdn.net/panguangyuu/article/details/87558417