tensorflow学习笔记(第一天)-MNIST机器学习入门

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a870542373/article/details/79930990

MNIST机器学习入门

这个是关于tensorflow的中文文档: http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_beginners.html
MNIST是一个入门级的计算机视觉数据集,这个就相当于编程语言中的"hello world",是入门级的。

一、首先是数据级: MNIST数据集 MNIST数据集的官网是http://yann.lecun.com/exdb/mnist/
自动下载的python代码为:input_data.py

"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
import gzip
import os
import tempfile
import numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
二、官方文档上给出的例子, 梯度下降算法(gradient descent algorithm),这个跑下来的正确率为91%,看文档说使用别的算法最高可以达到97%的正确率,暂时没有试验。
这个是方法对比的网址:http://rodrigob.github.io/are_we_there_yet/build/classification_datasets_results.html
下面给出代码:
import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import tensorflow as tf
#x不是一个特定的值,而是一个占位符placeholder,
#我们在TensorFlow运行计算时输入这个值。
#我们希望能够输入任意数量的MNIST图像,每一张图展平成784维的向量。
#我们用2维的浮点数张量来表示这些图,这个张量的形状是[None,784 ]。(这里的None表示此张量的第一个维度可以是任何长度的。)
x=tf.placeholder(tf.float32,[None,784])
#Variable 。 一个Variable代表一个可修改的张量,存在在TensorFlow的用于描述交互性操作的图中。
#它们可以用于计算输入值,也可以在计算中被修改。
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
#tf.matmul(​​X,W)表示x乘以W,
y = tf.nn.softmax(tf.matmul(x,W) + b)
y_ = tf.placeholder("float", [None,10])
#交叉熵是用来衡量我们的预测用于描述真相的低效性。
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
#梯度下降算法(gradient descent algorithm)以0.01的学习速率最小化交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
#初始化我们创建的变量:
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
#模型循环训练1000次!
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})
 
#tf.argmax 是一个非常有用的函数,它能给出某个tensor对象在某一维上的其数据最大值所在的索引值。
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
#为了确定正确预测项的比例,我们可以把布尔值转换成浮点数,然后取平均值。
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print( sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

跑出的结果为:

猜你喜欢

转载自blog.csdn.net/a870542373/article/details/79930990