第一个TF程序:MNIST案例简介

来自CloudWiki
Cloud17讨论 | 贡献2017年11月4日 (六) 04:33的版本 使用方法
跳转至: 导航搜索

这个教程的目标读者是对机器学习和TensorFlow都不太了解的新手。

当我们开始学习编程的时候,第一件事往往是学习打印"Hello World"。就好比编程入门有Hello World,机器学习入门有MNIST。

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

  • MNIST.png

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

在此教程中,我们将训练一个机器学习模型用于预测图片里面的数字。我们的目的不是要设计一个世界一流的复杂模型 -- 尽管我们会在之后给你源代码去实现一流的预测模型 -- 而是要介绍下如何使用TensorFlow。所以,我们这里会从一个很简单的数学模型开始,它叫做Softmax Regression。

对应这个教程的实现代码很短,而且真正有意思的内容只包含在三行代码里面。但是,去理解包含在这些代码里面的设计思想是非常重要的:TensorFlow工作流程和机器学习的基本概念。因此,这个教程会很详细地介绍这些代码的实现原理。


MNIST数据集

  • MNIST数据集的官网是Yann LeCun's website。在这里,我们提供了一份python源代码用于自动下载和安装这个数据集。
  • 源代码在GitHub上,下面也贴出源码:
# 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.
# ==============================================================================
"""Functions for downloading and reading MNIST data."""
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

使用方法

  • 将以上代码存为input_data.py文件
  • 新建test.py文件,与input_data.py在同一工程目录下
  • test.py内容如下:
#下载用于训练和测试的mnist数据集的源码
import input_data # 调用input_data
mnist = input_data.read_data_sets('data/', one_hot=True)
  • 运行test.py文件:
python test.py
  • 这时可以看到在同一目录下多了一个data目录,这就是下载的数据集:
(tensorflow) cloud@ubuntu:~/ai$ ls
data  hello.py  input_data.py  input_data.pyc  test.py
(tensorflow) cloud@ubuntu:~/ai$ ls data
t10k-images-idx3-ubyte.gz  train-images-idx3-ubyte.gz
t10k-labels-idx1-ubyte.gz  train-labels-idx1-ubyte.gz