MNIST数据集分类简单版本

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
mnist = input_data.read_data_sets("/data/stu05/mnist_data",one_hot=True)
 
 
Extracting /data/stu05/mnist_data/train-images-idx3-ubyte.gz
Extracting /data/stu05/mnist_data/train-labels-idx1-ubyte.gz
Extracting /data/stu05/mnist_data/t10k-images-idx3-ubyte.gz
Extracting /data/stu05/mnist_data/t10k-labels-idx1-ubyte.gz
 
#每个批次的大小
batch_size = 100
#计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size
#定义两个placeholder,None=100,28*28=784,即100行,784列
x = tf.placeholder(tf.float32,[None,784])
#0-9个输出标签
y = tf.placeholder(tf.float32,[None,10])
#创建一个简单的神经网络,只有输入层和输出层
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([1,10]))
#softmax函数转化为概率值
prediction = tf.nn.softmax(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()
#tf.equal()比较函数大小是否相同,相同为True,不同为false;tf.argmax():求y=1在哪个位置,求概率最大在哪个位置
#argmax返回一维张量中最大的值所在的位置,结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
#求准确率
#cast转化类型,将布尔型转化为32位浮点型,True=1.0,False=0.0;再求平均值
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
    sess.run(init)
    #将所有图片训练21次
    for epoch in range(21):
        #训练一次所有的图片
        for batch in range(n_batch):
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)
            #feed_dict传入训练集的图片和标签
            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})
        print("Iter"+str(epoch)+",Testing Accuracy:"+str(acc))
 
 
 
Iter0,Testing Accuracy:0.8303
Iter1,Testing Accuracy:0.8708
Iter2,Testing Accuracy:0.8821
Iter3,Testing Accuracy:0.8885
Iter4,Testing Accuracy:0.8941
Iter5,Testing Accuracy:0.8973
Iter6,Testing Accuracy:0.9001
Iter7,Testing Accuracy:0.9013
Iter8,Testing Accuracy:0.9038
Iter9,Testing Accuracy:0.9048
Iter10,Testing Accuracy:0.9068
Iter11,Testing Accuracy:0.9068
Iter12,Testing Accuracy:0.9084
Iter13,Testing Accuracy:0.9094
Iter14,Testing Accuracy:0.9097
Iter15,Testing Accuracy:0.9107
Iter16,Testing Accuracy:0.9118
Iter17,Testing Accuracy:0.9116
Iter18,Testing Accuracy:0.9127
Iter19,Testing Accuracy:0.9136
Iter20,Testing Accuracy:0.9146
 
 
 
 
 
 
 
posted @ 2017-12-03 22:15  爱学英语的程序媛  阅读(574)  评论(0编辑  收藏  举报