深度学习案例(三):Mnist数据集分类简单案例

MNIST数据集的官网是Yann LeCun’s website。下载数据包后放入工程目录下即可。

代码如下
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

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

# 每个批次的大小
batch_size = 100
# 计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size

# 定义两个placeholder
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])

# 创建一个简单的神经网络
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x, W) + b)
#prediction = tf.matmul(x, W) + b
# 二次代价函数
loss = tf.reduce_mean(tf.square(y - prediction))
# 使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

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

# 结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))  # argmax返回一维张量中最大的值所在的位置
# 求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#求b值
num_b=tf.reduce_mean(b)
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(21):
        for batch in range(n_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys})

        acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
        num=sess.run(num_b)
        print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))
#观察b的变化
        print('num'+'='+str(num))
运行结果:
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
Iter 0,Testing Accuracy 0.8325
num=-2.6077032e-09
Iter 1,Testing Accuracy 0.8702
num=-5.9604646e-09
Iter 2,Testing Accuracy 0.8819
num=-1.9371509e-08
Iter 3,Testing Accuracy 0.8879
num=-4.7683717e-08
Iter 4,Testing Accuracy 0.8946
num=-4.172325e-08
Iter 5,Testing Accuracy 0.8967
num=-3.576279e-08
Iter 6,Testing Accuracy 0.8999
num=-5.066395e-08
Iter 7,Testing Accuracy 0.9017
num=-8.642674e-08
Iter 8,Testing Accuracy 0.9029
num=-7.4505806e-08
Iter 9,Testing Accuracy 0.9047
num=-8.940697e-08
Iter 10,Testing Accuracy 0.9064
num=-5.066395e-08
Iter 11,Testing Accuracy 0.9075
num=-9.23872e-08
Iter 12,Testing Accuracy 0.9079
num=-1.2814999e-07
Iter 13,Testing Accuracy 0.9093
num=-1.3113022e-07
Iter 14,Testing Accuracy 0.9098
num=-8.34465e-08
Iter 15,Testing Accuracy 0.9109
num=-1.013279e-07
Iter 16,Testing Accuracy 0.9112
num=-1.0728836e-07
Iter 17,Testing Accuracy 0.9129
num=-5.364418e-08
Iter 18,Testing Accuracy 0.9127
num=-6.556511e-08
Iter 19,Testing Accuracy 0.9129
num=-1.2516975e-07
Iter 20,Testing Accuracy 0.915
num=-1.6093254e-07

Process finished with exit code 0


你可能感兴趣的:(深度学习案例(三):Mnist数据集分类简单案例)