天天看点

tensorflow初学之MNIST中文版文档存在的小问题: 其他概念及公式:代码位置源码分析:结果

这里借助极客学院的中文文档帮助:中文帮助文档链接,以及英文帮助文档:英文帮助文档链接(此处需要FQ,你懂得)

中文版文档存在的小问题:

对照中英文版学习,因为我发现中文文档细节有些地方翻译的不够精准;

此外,中文帮助文档MNIST入门章节中使用了已经被废弃的函数initialize_all_variables()

(虽然他在下一节深入MNIST一节中使用的是最新的函数,但是废弃的函数还是应该给予说明,特别是在新手入门这一节中),

英文文档中关于该函数介绍如下:

tf.initialize_all_variables(*args, **kwargs)(deprecated)
THIS FUNCTION IS DEPRECATED. It will be removed after 2017-03-02. Instructions for updating: Use tf.global_variables_initializer instead.
(            
tf.initialize_all_variables将被tf.global_variables_initializer代替
           

最新的tensorflow中使用的是

最新的tensorflow中使用的是

MNIST

详细介绍可看帮助文档

MNIST是一个入门级的计算机视觉数据集,包含各种手写数字图片,像这样:

tensorflow初学之MNIST中文版文档存在的小问题: 其他概念及公式:代码位置源码分析:结果

它也包含每一张图片对应的标签,告诉我们这个是数字几。比如,上面这四张图片的标签分别是5,0,4,1。

在MNIST训练数据集中,

mnist.train.images

是一个形状为

[60000, 784]

的张量,第一个维度数字用来索引图片,第二个维度数字用来索引每张图片中的像素点。在此张量里的每一个元素,都表示某张图片里的某个像素的强度值,值介于0和1之间。

相对应的MNIST数据集的标签是介于0到9的数字,用来描述给定图片里表示的数字。为了用于这个教程,我们使标签数据是"one-hot vectors"。 一个one-hot向量除了某一位的数字是1以外其余各维度数字都是0。所以在此教程中,数字n将表示成一个只有在第n维度(从0开始)数字为1的10维向量。比如,标签0将表示成([1,0,0,0,0,0,0,0,0,0,0])。因此,

mnist.train.labels

是一个

[60000, 10]

的数字矩阵。

介绍完MNIST概念,接下来要学习一个数学模型叫做:Softmax Regression。

其他概念及公式:

看中文版帮助文档即可

代码位置

之前我是借助anaconda3安装的tensorflow(我的电脑是Python2和python3共存,anaconda2和anaconda3共存),

mnist示例程序位于(附上链接:input_data.py下载,mnist_softmax.py下载):

..\anaconda2\envs\py3\Lib\site-packages\tensorflow\examples\tutorials\mnist
           

找到官方源码示例,如图:

tensorflow初学之MNIST中文版文档存在的小问题: 其他概念及公式:代码位置源码分析:结果

源码分析:

input_data.py:

#实现的功能就是从自动下载和读取 MNIST数据
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

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
           

mnist_softmax.py:

1.下载数据集

先将

input_data导入到项目文件夹下,然后利用下列代码导入到你的项目中

import tensorflow.examples.tutorials.mnist.input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
           

或者直接粘贴到你的程序中;

2.构建模型

"""
  x不是一个特定的值,而是一个占位符placeholder,我们在TensorFlow运行计算时输入这个值;

 用2维的浮点数张量来表示这些图,所以用float32;

 None表示此张量的第一个维度可以是任何长度的,即可以输入任意数量的MNIST图像;

 由于每一张图片包含28X28个像素点,我们可以用一个数字数组28*28=784来表示这张图片: 

  """
  x = tf.placeholder(tf.float32, [None, 784])
           
"""
  初始化权重值W   
  一个Variable代表一个可修改的张量
  用784维的图片向量乘以它以得到一个10维的证据值向量,每一位对应不同数字类
  """
  W = tf.Variable(tf.zeros([784, 10]))
           
"""
  bi表示数字i类的偏置量,其形状是[10],所以我们可以直接把它加到输出上面。
  """
  b = tf.Variable(tf.zeros([10]))
           
#创建softmax回归模型
  y = tf.matmul(x, W) + b
           

3.训练模型

引入成本函数“cross-entropy 交叉熵”

# 定义损失和优化器
  y_ = tf.placeholder(tf.float32, [None, 10])
           
#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
  #                                 reduction_indices=[1]))
  #提供的 cross-entropy规则求出的数值不稳定
  #所以这里我们使用 tf.nn.softmax_cross_entropy_with_logits 来产生y,然后求平均值
  cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))
           
#设置TensorFlow用梯度下降算法(gradient descent algorithm)以0.01的学习速率最小化交叉熵
  train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
           

接下来,就是开始说的中文文档和英文文档的不同之处,这里我们采用最新源码,借助英文文档理解

#定义一个InteractiveSession类,它是命令解析器,类似tf.session必须定义,才能使用相关操作
  sess = tf.InteractiveSession()
           

关于 tf.Session() 和tf.InteractiveSession() 的区别,点击查看

# 训练开始
  tf.global_variables_initializer().run()
           
#这里让模型训练1000*10=1000次
  for _ in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
           

4.模型评估

"""
  tf.argmax(y, 1)返回的是模型对于任一输入x预测到的标签值,tf.argmax(y_,1) 代表正确的标签,
  我们可以用 tf.equal 来检测我们的预测是否真实标签匹配(索引位置一样表示匹配)。
  返回的是布尔值
 """
  correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
           
"""
  这行代码会给我们一组布尔值。为了确定正确预测项的比例,我们可以把布尔值转换成浮点数,然后取平均值。
  例如,[True, False, True, True] 会变成 [1,0,1,1] ,取平均值后得到 0.75.
  """
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
           
#输出学习到的模型在测试数据集上面的正确率。
  print(sess.run(accuracy, feed_dict={x: mnist.test.images,
                                      y_: mnist.test.labels}))
           

5.主函数

"""
  argparse是Python标准库中推荐使用的编写命令行程序的工具;
  1.
  add_argument()方法,用来设置程序可接受的命令行参数;type设置类型
  help这里设置打印的是输入数据的路径
  2.parser.parse_known_args() 从我们的命令行参数中返回了一些数据,即add_argument方法中设置的参数
  3.tf.app.run(main=a,argv=b),选择参数列表b和函数a运行程序
  
  """
if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()   
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
           

6.完整代码如下:

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""A very simple MNIST classifier.

See extensive documentation at
http://tensorflow.org/tutorials/mnist/beginners/index.md
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

# Import data
from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None


def main(_):
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])
  W = tf.Variable(tf.zeros([784, 10]))
  b = tf.Variable(tf.zeros([10]))
  y = tf.matmul(x, W) + b

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [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.nn.softmax_cross_entropy_with_logits on the raw
  # outputs of 'y', and then average across the batch.
  cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))

  #设置TensorFlow用梯度下降算法(gradient descent algorithm)以0.01的学习速率最小化交叉熵
  train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

  sess = tf.InteractiveSession()
  # Train
  tf.global_variables_initializer().run()
  for _ 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))
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  print(sess.run(accuracy, feed_dict={x: mnist.test.images,
                                      y_: mnist.test.labels}))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
           

结果

tensorflow初学之MNIST中文版文档存在的小问题: 其他概念及公式:代码位置源码分析:结果

如图所示,正确率为91.6%,结果并不好,但是这里我们只是为了学会简单模型的使用,在随后的学习,再考虑使用其他模型。

继续阅读