博客园  :: 首页  :: 新随笔  :: 管理

MNIST手写数字分类simple版(03-2)

Posted on 2020-02-15 01:16  wsg_blog  阅读(1330)  评论(0编辑  收藏  举报

simple版本nn模型 训练手写数字处理

 

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

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(20):
        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))

如果我们把上边代码的二次代价函数换成下边这行代码,其余不变,得到的结果会更好一些,具体原因看下篇博客 对交叉墒和二次代价函数的介绍

 loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))

 

 

目录:

  1. tensorflow简介、目录
  2. tensorflow中的图(02-1)
  3. tensorflow变量的使用(02-2)
  4. tensorflow中的Fetch、Feed(02-3)
  5. tensorflow版helloworld---拟合线性函数的k和b(02-4)
  6. tensorflow非线性回归(03-1)
  7. MNIST手写数字分类simple版(03-2)
  8. 二次代价函数、交叉熵(cross-entropy)、对数似然代价函数(log-likelihood cost)(04-1)
  9. 多层网络通过防止过拟合,增加模型的准确率(04-2)
  10. 修改优化器进一步提升准确率(04-3)
  11. 手写数字识别-卷积神经网络cnn(06-2)
  12. 循环神经网络rnn与长短时记忆神经网络简述(07-2)
  13. 循环神经网络lstm代码实现(07-3)
  14. tensorflow模型保存和使用08
  15. 下载inception v3  google训练好的模型并解压08-3
  16. 使用inception v3做各种图像分类识别08-4
  17. word2vec模型训练简单案例
  18. word2vec+textcnn文本分类简述及代码