【Tensorflow】Mnist手写数字识别

环境

python=3.6
tensorflow=1.14
opencv=3.4.2
numpy

数据下载

由于自身的API下载一直报错,我使用了其他框架下的下载数据模块,新建dataset.py,代码如下:

# Copyright 2015 Google Inc. 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 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/'
def maybe_download(filename, work_directory):
    """Download the data from Yann's website, unless it's already here."""
    if not os.path.exists(work_directory):
        os.mkdir(work_directory)
    filepath = os.path.join(work_directory, filename)
    if not os.path.exists(filepath):
        filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)
        statinfo = os.stat(filepath)
        print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
    return filepath
def _read32(bytestream):
    dt = numpy.dtype(numpy.uint32).newbyteorder('>')
    return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
def extract_images(filename):
    """Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
    print('Extracting', filename)
    with gzip.open(filename) as bytestream:
        magic = _read32(bytestream)
        if magic != 2051:
            raise ValueError('Invalid magic number %d in MNIST image file: %s' %
                (magic, filename))
        num_images = _read32(bytestream)
        rows = _read32(bytestream)
        cols = _read32(bytestream)
        buf = bytestream.read(rows * cols * num_images)
        data = numpy.frombuffer(buf, dtype=numpy.uint8)
        data = data.reshape(num_images, rows, cols, 1)
    return data

def dense_to_one_hot(labels_dense, num_classes=10):
    """Convert class labels from scalars to one-hot vectors."""
    num_labels = labels_dense.shape[0]
    index_offset = numpy.arange(num_labels) * num_classes
    labels_one_hot = numpy.zeros((num_labels, num_classes))
    labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
    return labels_one_hot

def extract_labels(filename, one_hot=False):
    """Extract the labels into a 1D uint8 numpy array [index]."""
    print('Extracting', filename)
    with gzip.open(filename) as bytestream:
        magic = _read32(bytestream)
        if magic != 2049:
            raise ValueError(
                'Invalid magic number %d in MNIST label file: %s' %
                (magic, filename))
        num_items = _read32(bytestream)
        buf = bytestream.read(num_items)
        labels = numpy.frombuffer(buf, dtype=numpy.uint8)
        if one_hot:
            return dense_to_one_hot(labels)
        return labels

class DataSet(object):
    def __init__(self, images, labels, fake_data=False, one_hot=False,
               dtype=tf.float32):
        """Construct a DataSet.
        one_hot arg is used only if fake_data is true.  `dtype` can be either
        `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
        `[0, 1]`.
        """
        dtype = tf.as_dtype(dtype).base_dtype
        if dtype not in (tf.uint8, tf.float32):
            raise TypeError('Invalid image dtype %r, expected uint8 or float32' %
                      dtype)
        if fake_data:
            self._num_examples = 10000
            self.one_hot = one_hot
        else:
            assert images.shape[0] == labels.shape[0], (
                'images.shape: %s labels.shape: %s' % (images.shape,
                                                 labels.shape))
            self._num_examples = images.shape[0]
            # Convert shape from [num examples, rows, columns, depth]
            # to [num examples, rows*columns] (assuming depth == 1)
            assert images.shape[3] == 1
            images = images.reshape(images.shape[0],
                              images.shape[1] * images.shape[2])
            if dtype == tf.float32:
                # Convert from [0, 255] -> [0.0, 1.0].
                images = images.astype(numpy.float32)
                images = numpy.multiply(images, 1.0 / 255.0)
        self._images = images
        self._labels = labels
        self._epochs_completed = 0
        self._index_in_epoch = 0

    @property
    def images(self):
        return self._images
    @property
    def labels(self):
        return self._labels
    @property
    def num_examples(self):
        return self._num_examples
    @property
    def epochs_completed(self):
        return self._epochs_completed

    def next_batch(self, batch_size, fake_data=False):
        """Return the next `batch_size` examples from this data set."""
        if fake_data:
            fake_image = [1] * 784
            if self.one_hot:
                fake_label = [1] + [0] * 9
            else:
                fake_label = 0
            return [fake_image for _ in xrange(batch_size)], [
              fake_label for _ in xrange(batch_size)]
        start = self._index_in_epoch
        self._index_in_epoch += batch_size
        if self._index_in_epoch > self._num_examples:
            # Finished epoch
            self._epochs_completed += 1
            # Shuffle the data
            perm = numpy.arange(self._num_examples)
            numpy.random.shuffle(perm)
            self._images = self._images[perm]
            self._labels = self._labels[perm]
            # Start next epoch
            start = 0
            self._index_in_epoch = batch_size
            assert batch_size <= self._num_examples
        end = self._index_in_epoch
        return self._images[start:end], self._labels[start:end]

def read_data_sets(train_dir, fake_data=False, one_hot=False, dtype=tf.float32):
    class DataSets(object):
        pass
    data_sets = DataSets()
    if fake_data:
        def fake():
            return DataSet([], [], fake_data=True, one_hot=one_hot, dtype=dtype)
        data_sets.train = fake()
        data_sets.validation = fake()
        data_sets.test = fake()
        return data_sets
    TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
    TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
    TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
    TEST_LABELS = 't10k-labels-idx1-ubyte.gz'
    VALIDATION_SIZE = 5000
    local_file = maybe_download(TRAIN_IMAGES, train_dir)
    train_images = extract_images(local_file)
    local_file = maybe_download(TRAIN_LABELS, train_dir)
    train_labels = extract_labels(local_file, one_hot=one_hot)
    local_file = maybe_download(TEST_IMAGES, train_dir)
    test_images = extract_images(local_file)
    local_file = maybe_download(TEST_LABELS, train_dir)
    test_labels = extract_labels(local_file, one_hot=one_hot)
    validation_images = train_images[:VALIDATION_SIZE]
    validation_labels = train_labels[:VALIDATION_SIZE]
    train_images = train_images[VALIDATION_SIZE:]
    train_labels = train_labels[VALIDATION_SIZE:]
    data_sets.train = DataSet(train_images, train_labels, dtype=dtype)
    data_sets.validation = DataSet(validation_images, validation_labels,
                                 dtype=dtype)
    data_sets.test = DataSet(test_images, test_labels, dtype=dtype)
    return data_sets

下载mnist数据

import tensorflow as tf
import dataset
import os
import cv2
import numpy as np


print("start download mnist data......")
mnist = dataset.read_data_sets('MNIST_data', one_hot=True)

训练

# 定义模型保存路径
model_path = "./model"
if os.path.isdir(model_path) == False:
    os.makedirs(model_path)
# 定义测试结果图像保存路径
result_path = "./img"
if os.path.isdir(result_path) == False:
    os.makedirs(result_path)

def network(X_holder):
    # 定义训练输入img占位符
    X_images = tf.reshape(X_holder, [-1, 28, 28, 1])
    #convolutional layer 1, 第一层卷积层
    # 权重参数
    conv1_Weights = tf.Variable(tf.truncated_normal([5, 5, 1, 32], stddev=0.1))
    # 偏置项参数
    conv1_biases = tf.Variable(tf.constant(0.1, shape=[32]))
    conv1_conv2d = tf.nn.conv2d(X_images, conv1_Weights, strides=[1, 1, 1, 1], padding='SAME') + conv1_biases
    # 激活层
    conv1_activated = tf.nn.relu(conv1_conv2d)
    # 池化层
    conv1_pooled = tf.nn.max_pool(conv1_activated, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    #convolutional layer 2,第2层卷积层
    conv2_Weights = tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=0.1))
    conv2_biases = tf.Variable(tf.constant(0.1, shape=[64]))
    conv2_conv2d = tf.nn.conv2d(conv1_pooled, conv2_Weights, strides=[1, 1, 1, 1], padding='SAME') + conv2_biases
    conv2_activated = tf.nn.relu(conv2_conv2d)
    conv2_pooled = tf.nn.max_pool(conv2_activated, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    #full connected layer 1, 全链接层
    # 将三维结果拉平
    connect1_flat = tf.reshape(conv2_pooled, [-1, 7 * 7 * 64])
    # 全链接层权重
    connect1_Weights = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1024], stddev=0.1))
    # 全链接偏置项
    connect1_biases = tf.Variable(tf.constant(0.1, shape=[1024]))
    connect1_Wx_plus_b = tf.add(tf.matmul(connect1_flat, connect1_Weights), connect1_biases)
    # 激活层
    connect1_activated = tf.nn.relu(connect1_Wx_plus_b)
    #full connected layer 2, 第二层全链接层
    connect2_Weights = tf.Variable(tf.truncated_normal([1024, 10], stddev=0.1))
    connect2_biases = tf.Variable(tf.constant(0.1, shape=[10]))
    connect2_Wx_plus_b = tf.add(tf.matmul(connect1_activated, connect2_Weights), connect2_biases)
    predict_y = tf.nn.softmax(connect2_Wx_plus_b)
    return predict_y

def train():
    X_holder = tf.placeholder(tf.float32)

    predict_y = network(X_holder)
    # 定义训练输入label占位符
    y_holder = tf.placeholder(tf.float32)
    #loss and train, loss桉树,这里使用平均
    loss = tf.reduce_mean(-tf.reduce_sum(y_holder * tf.log(predict_y), 1))
    # 优化器,使用adam
    optimizer = tf.train.AdamOptimizer(0.0001)
    train = optimizer.minimize(loss)

    init = tf.global_variables_initializer()
    session = tf.Session()
    session.run(init)
    saver=tf.train.Saver(max_to_keep=5)
    max_acc = 0
    """
    下面是训练的过程,10001表示训练1000次,可以手动修改
    """
    for i in range(1001):
        """
        加载训练的数据,200表示每次训练加载200条数据,可以修改
        """
        train_images, train_labels = mnist.train.next_batch(200)
        session.run(train, feed_dict={X_holder:train_images, y_holder:train_labels})
        """
        每100次测试一次并使用测试的正确率决定是否保存模型,如果由于之前的就保存,比之前的差不保存
        """
        if i % 100 == 0:
            correct_prediction = tf.equal(tf.argmax(predict_y, 1), tf.argmax(y_holder, 1))
            accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
            test_images, test_labels = mnist.test.next_batch(2000)
            # 计算训练的正确率和测试的正确率
            train_accuracy = session.run(accuracy, feed_dict={X_holder:train_images, y_holder:train_labels})
            test_accuracy = session.run(accuracy, feed_dict={X_holder:test_images, y_holder:test_labels})
            print('step:%d train accuracy:%.4f test accuracy:%.4f' %(i, train_accuracy, test_accuracy))
            if test_accuracy > max_acc:
                max_acc = test_accuracy
                saver.save(session, '{}/mnist_{}.ckpt'.format(model_path, str(i)), global_step=i + 1)

测试

def test():
    X_holder = tf.placeholder(tf.float32)

    predict_y = network(X_holder)
    # 定义训练输入label占位符
    y_holder = tf.placeholder(tf.float32)

    # 加载模型
    init = tf.global_variables_initializer()
    session = tf.Session()
    session.run(init)
    saver = tf.train.Saver(max_to_keep=5)
    # 加载最优模型
    model_file = tf.train.latest_checkpoint(model_path)
    saver.restore(session, model_file)
    # 计算正确率
    correct_prediction = tf.equal(tf.argmax(predict_y, 1), tf.argmax(y_holder, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    """
    获取测试图像,数量2000可以更改
    """
    test_images, test_labels = mnist.test.next_batch(2000)
    test_accuracy, result = session.run([accuracy, predict_y], feed_dict={X_holder: test_images, y_holder: test_labels})
    # 保存测试的图像和结果,图像名以序号和预测结果命名
    for i in range(len(test_images)):
        # 由于预测图像有过归一化,这里还原成原本图像
        img = test_images[i] * 255.0
        img = np.reshape(img,  [28, 28])
        label = np.argmax(result[i])
        cv2.imwrite("{}/{}.png".format(result_path, str(i)+"_"+str(label)), img)

    print("test accuary is: {};".format(test_accuracy))

代码运行入口

可选择训练还是测试

if __name__ == "__main__":
    """
    训练为True,测试为False
    """
    is_trin = True
    if is_trin:
        train()
    else:
        test()

训练结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值