MINIST数据集分类简单版本(03-3)

MNIST_data数据   百度网盘链接:https://pan.baidu.com/s/19lhmrts-vz0-w5wv2A97gg
提取码:cgnx

# -*- coding: UTF-8 -*-

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([1,10]))
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()
 
#结果放在一个布尔型列表中
correct_prediction=tf.equal(tf.argmax(y,1), tf.argmax(prediction,1)) #argmax函数返回一维向量中最大值所在的位置
#求准确率
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
 
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(21):#把所有图片训练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})
        print("Iter"+str(epoch)+",Testing Accuracy "+str(acc))

运行结果

上面代码有很多地方都可以优化,如何介绍把识别的准确率提高到95%以上

posted @ 2020-04-19 17:22  小孢子  阅读(523)  评论(0编辑  收藏  举报