TensorFlow手写数字识别mnist example源码分析
TensorFlow 默认安装在 /usr/lib/Python/site-packages/tensorflow/
实例文件位于tensorflow/models/image/mnist/convolutional.py,为TensorFlow自带的example文件。
# 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.
# ==============================================================================
"""Simple, end-to-end, LeNet-5-like convolutional MNIST model example.
This should achieve a test error of 0.7%. Please keep this model as simple and
linear as possible, it is meant as a tutorial for simple convolutional models.
Run with --self_test on the command line to execute a short self-test.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import gzip
import os
import sys
import time
import numpy
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/' # 数据源
WORK_DIRECTORY = 'data' # 工作目录,存放下载的数据
# MNIST 数据集特征:
# 图像尺寸 28x28
IMAGE_SIZE = 28
NUM_CHANNELS = 1 # 黑白图像
PIXEL_DEPTH = 255 # 像素值0~255
NUM_LABELS = 10 # 标签分10个类别
VALIDATION_SIZE = 5000 # 验证集大小
SEED = 66478 # 随机数种子,可设为 None 表示真的随机
BATCH_SIZE = 64 # 批处理大小为64
NUM_EPOCHS = 10 # 数据全集一共过10遍网络
EVAL_BATCH_SIZE = 64 # 验证集批处理大小也是64
# 验证时间间隔,每训练100个批处理,做一次评估
EVAL_FREQUENCY = 100 # Number of steps between evaluations.
FLAGS = None
def data_type():
"""Return the type of the activations, weights, and placeholder variables."""
if FLAGS.use_fp16:
return tf.float16
else:
return tf.float32
def maybe_download(filename):
"""如果下载过了数据,就不再重复下载"""
if not tf.gfile.Exists(WORK_DIRECTORY):
tf.gfile.MakeDirs(WORK_DIRECTORY)
filepath = os.path.join(WORK_DIRECTORY, filename)
if not tf.gfile.Exists(filepath):
filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)
with tf.gfile.GFile(filepath) as f:
si