基于softmax的mnist数字识别

# Title     : TODO
# Objective : TODO
# Created by: Chen Da
# Created on: 2018/10/17


import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


#导入数据
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/Users/chenda/Desktop/Notes/Python_Note/15_深度学习/data/",one_hot=True)

# #查看训练数据的大小
# print(mnist.train.images.shape)
# print(mnist.train.labels.shape)
# #查看验证集数据大小
# print(mnist.validation.images.shape)
# print(mnist.validation.labels.shape)
# #查看测试集数据大小
# print(mnist.test.images.shape)
# print(mnist.test.labels.shape)
#
# #打印第0张训练图片对应的向量表示
# print(mnist.train.images[0,:])
#
#
# #将MNIST数据读取并保存为图片
# import scipy.misc
#
# save_dir = "/Users/chenda/Desktop/"
#
# #保存前20张图片
# for i in range(20):
#     image_array = mnist.train.images[i,:]
#     image_array = image_array.reshape(28,28)
#     file_name = save_dir + "mnist_train_%s.jpg"%i
#     scipy.misc.toimage(image_array,cmin=0.0,cmax=0.0).save(file_name)


# #打印前20张图片的标签
# for i in range(20):
#     image_label = mnist.train.labels[i,:]
#     print(image_label)



#创建占位符x,代表识别的图片
x = tf.placeholder(tf.float32,[None,784])

#Softmax模型的参数
W = tf.Variable(tf.zeros([784,10]))         #将784维的输入转换成10维的输出
b = tf.Variable(tf.zeros([10]))             #偏置项

#y表示模型的输出
y = tf.nn.softmax(tf.matmul(x,W) + b)

#y_是实际的图像标签
y_ = tf.placeholder(tf.float32,[None,10])

#构造交叉熵损失
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y)))

#梯度下降对损失函数进行优化
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

#创建会话
with tf.Session() as sess:
    tf.global_variables_initializer().run()

    #进行一千步梯度下降
    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})

    #检验预测结果
    correct_pre = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))      #取出数组中最大值的下标,将独热表示和模型输出转换为数字标签。
    accuracy = tf.reduce_mean(tf.cast(correct_pre,tf.float32))  #cast将布尔值转换成float变量

    print(sess.run(accuracy,feed_dict={x:mnist.test.images,y_:mnist.test.labels}))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值