tensorflow入门实现Mnist手写数据集分类(单层NN)

内容参考http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_beginners.html,本文内容只是方便自己下次学习,如有侵权,请联系我进行删除。

一、Tensorflow安装

我前面有些在ubuntu下安装GPU:https://blog.csdn.net/qq_33266320/article/details/79626176

装好GPU,在装anaconda,然后直接pip install tensorflow_gpu就可以了。

window下建议装anaconda然后在装gpu在一样得命名。

如果是CPU,直接pip install tensorflow(可以==版本号)

二、在tensorflow资源上引入Mnist数据

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)
print(mnist.train.images.shape,mnist.train.labels.shape)#55000
print(mnist.test.images.shape,mnist.test.labels.shape)#10000
print(mnist.validation.images.shape,mnist.validation.labels.shape)#5000

三、创建模型

#Create model
x=tf.placeholder(tf.float32,[None,784])#占位符
W=tf.Variable(tf.zeros([784,10]))#参数变量
b=tf.Variable(tf.zeros([10]))
y=tf.nn.softmax(tf.matmul(x,W)+b)

y_ = tf.placeholder("float", [None,10])

 # The raw formulation of cross-entropy,
  #
  #   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
  #                                 reduction_indices=[1]))
  #
  # can be numerically unstable.
  #
  # So here we use tf.losses.sparse_softmax_cross_entropy on the raw
  # outputs of 'y', and then average across the batch.
#cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=y_, logits=y)
cross_entropy = -tf.reduce_sum(y_*tf.log(y))

train_step=tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)#
四、开始训练
sess=tf.InteractiveSession()
#sess.tf.Session()
tf.global_variables_initializer().run()
#init = tf.initialize_all_variables()
#sess = tf.Session()
#sess.run(init)
#train
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

五、评估

#test trained model
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_,1))#选最大arg
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(
      accuracy, feed_dict={
          x: mnist.test.images,
          y_: mnist.test.labels
      }))
在学习率为0.01下在我电脑上运行该代码准确率是92.01%。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值