python tensorflow 使用minist数据集实现手写数字识别

来源:互联网 发布:java 爬虫框架比较 编辑:程序博客网 时间:2024/04/26 20:10

这个是大牛写的,怕以后找不到了,所以做个保存

二话不说上代码:

# -*- coding: utf-8 -*-import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data# 下载MINIST数据集mnist = input_data.read_data_sets('MNIST_data', one_hot=True)# None表示输入任意数量的MNIST图像,每一张图展平成784维的向量# placeholder是占位符,在训练时指定x = tf.placeholder(tf.float32, [None, 784])# 初始化W,b矩阵W = tf.Variable(tf.zeros([784, 10]))b = tf.Variable(tf.zeros([10]))# tf.matmul(​​X,W)表示x乘以Wy = tf.nn.softmax(tf.matmul(x, W) + b)# 为了计算交叉熵,我们首先需要添加一个新的占位符用于输入正确值y_ = tf.placeholder("float", [None, 10])# 交叉熵损失函数cross_entropy = -tf.reduce_sum(y_*tf.log(y))# 模型的训练,不断的降低成本函数# 要求TensorFlow用梯度下降算法(gradient descent algorithm)以0.01的学习速率最小化交叉熵train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)# 在运行计算之前,需要添加一个操作来初始化我们创建的变量init = tf.global_variables_initializer()# 在Session里面启动我模型,并且初始化变量sess = tf.Session()sess.run(init)# 开始训练模型,循环训练1000次for i in range(50):    # 随机抓取训练数据中的100个批处理数据点    batch_xs, batch_ys = mnist.train.next_batch(100)    # 然后我们用这些数据点作为参数替换之前的占位符来运行train_step    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})# 检验真实标签与预测标签是否一致correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))# 计算精确度,将true和false转化成相应的浮点数,求和取平均accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))# 计算所学习到的模型在测试数据集上面的正确率print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

精度能到0.88,亲测……

阅读全文
0 0
原创粉丝点击