mnist手写阿拉伯数字的识别
训练集: train-images.idx3-ubyte 包含了 60000 个手写文字的图片,每个图片只包含一个阿拉 伯数字,train-labels.idx1-ubyte 文件给出了每个图片对应的阿拉伯数字。这两个文件构成了 结业作业的训练集。使用这两个文件中的数据训练一个分类器,当将一个不在训练数据中的 阿拉伯数字图片输入该分类器时,分类器可以反馈该图片中的阿拉伯数字。
测试集:将 t10k-images.idx3-ubyte 文件中的图片输入给你训练的分类器,将返回的识别结果 与 t10k-labels.idx1-ubyte 文件中的标签对比,正确识别的图片个数除于测试集中的总图片数 (10000 张),即为识别准确率。
通过input_data.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 tensorflow.python.platform
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
CNN
import tensorflow as tf
import input_data # download and extract the data set automatically
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# get the data source
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# input image:pixel 28*28 = 784
with tf.name_scope('input'):
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder('float', [None, 10]) # y_ is realistic result
with tf.name_scope('image'):
x_image = tf.reshape(x, [-1, 28, 28, 1]) # any dim, width, height, channel(depth)
tf.summary.image('input_image', x_image, 8)
# the first convolution layer
with tf.name_scope('conv_layer1'):
W_conv1 = weight_variable([5, 5, 1, 32]) # convolution kernel: 5*5*1, number of kernel: 32
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # make convolution, output: 28*28*32
with tf.name_scope('pooling_layer'):
h_pool1 = max_pool_2x2(h_conv1) # make pooling, output: 14*14*32
# the second convolution layer
with tf.name_scope('conv_layer2'):
W_conv2 = weight_variable([5, 5, 32, 64]) # convolution kernel: 5*5, depth: 32, number of kernel: 64
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output: 14*14*64
with tf.name_scope('pooling_layer'):
h_pool2 = max_pool_2x2(h_conv2) # output: 7*7*64
# the first fully connected layer
with tf.name_scope('fc_layer3'):
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024]) # size: 1*1024
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # output: 1*1024
# dropout
with tf.name_scope('dropout'):
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# the second fully connected layer
# train the model: y = softmax(x * w + b)
with tf.name_scope('output_fc_layer4'):
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10]) # size: 1*10
with tf.name_scope('softmax'):
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # output: 1*10
with tf.name_scope('lost'):
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
tf.summary.scalar('lost', cross_entropy)
with tf.name_scope('train'):
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
with tf.name_scope('accuracy'):
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
tf.summary.scalar('accuracy', accuracy)
merged = tf.summary.merge_all()
train_summary = tf.summary.FileWriter(r'D:\pycharm\PyCharm Community Edition 2019.1.2\阿拉伯数字recognition', tf.get_default_graph())
# init all variables
init = tf.global_variables_initializer()
# run session
with tf.Session() as sess:
sess.run(init)
# train data: get w and b
for i in range(2300): # train 2000 times
batch = mnist.train.next_batch(50)
result, _ = sess.run([merged, train_step], feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
# train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
if i % 100 == 0:
# train_accuracy = sess.run(accuracy, feed_dict)
train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) # no dropout
print('step %d, training accuracy %g' % (i, train_accuracy))
# result = sess.run(merged, feed_dict={x: batch[0], y_: batch[1]})
train_summary.add_summary(result, i)
train_summary.close()
print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
# open tensor_board in windows-cmd
# tensorboard --logdir=C:\Users\Administrator\tf
逻辑回归
import tensorflow as tf
# from tensorflow.examples.tutorials.mnist import input_data
import input_data
# 读入数据 ‘MNIST_data’ 是我保存数据的文件夹的名称
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 各种图片数据以及标签 images是图像数据 labels 是正确的结果
trainimg = mnist.train.images
trainlabels = mnist.train.labels
testimg = mnist.test.images
testlabels = mnist.test.labels
# 输入的数据 每张图片的大小是 28 * 28,在提供的数据集中已经被展平乘了 1 * 784(28 * 28)的向量
# 方便矩阵乘法处理
x = tf.placeholder(tf.float32, [None, 784])
# 输出的结果是对于每一张图输出的是 1*10 的向量,例如 [1, 0, 0, 0...]
# 只有一个数字是1 所在的索引表示预测数据
y = tf.placeholder(tf.float32, [None, 10])
# 模型参数
# 对于这样的全连接方式 某一层的参数矩阵的行数是输入数据的数量 ,列数是这一层的神经元个数
# 这一点用线性代数的思想考虑会比较好理解
W = tf.Variable(tf.zeros([784, 10]))
# 偏置
b = tf.Variable(tf.zeros([10]))
# 建立模型 并使用softmax()函数对输出的数据进行处理
# softmax() 函数比较重要 后面写
# 这里注意理解一下 模型输出的actv的shape 后边会有用(n * 10, n时输入的数据的数量)
actv = tf.nn.softmax(tf.matmul(x, W) + b)
# 损失函数 使用交叉熵的方式 softmax()函数与交叉熵一般都会结合使用
# clip_by_value()函数可以将数组整理在一个范围内,后面会具体解释
cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(tf.clip_by_value(actv, 1e-10, 1.0)), reduction_indices=1))
# 使用梯度下降的方法进行参数优化
learning_rate = 0.01
optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# 判断是否预测结果与正确结果是否一致
# 注意这里使用的函数的 argmax()也就是比较的是索引 索引才体现了预测的是哪个数字
# 并且 softmax()函数的输出不是[1, 0, 0...] 类似的数组 不会与正确的label相同
# pred 数组的输出是 [True, False, True...] 类似的
pred = tf.equal(tf.argmax(actv, 1), tf.argmax(y, 1))
# 计算正确率
# 上面看到pred数组的形式 使用cast转化为浮点数 则 True会被转化为 1.0, False 0.0
# 所以对这些数据求均值 就是正确率了(这个均值表示所有数据中有多少个1 -> True的数量 ->正确个数)
accr = tf.reduce_mean(tf.cast(pred, tf.float32))
init_op = tf.global_variables_initializer()
# 接下来要使用的一些常量 可能会自己根据情况调整所以都定义在这里
training_epochs = 50 # 一共要训练的轮数
batch_size = 100 # 每一批训练数据的数量
display_step = 5 # 用来比较、输出结果
with tf.Session() as sess:
sess.run(init_op)
# 对于每一轮训练
for epoch in range(training_epochs):
avg_cost = 0.
# 计算训练数据可以划分多少个batch大小的组
num_batch = int(mnist.train.num_examples / batch_size)
# 每一组每一组地训练
for i in range(num_batch):
# 这里地 mnist.train.next_batch()作用是:
# 第一次取1-10数据 第二次取 11-20 ... 类似这样
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# 运行模型进行训练
sess.run(optm, feed_dict={x: batch_xs, y: batch_ys})
# 如果觉得上面 feed_dict 的不方便 也可以提前写在外边
feeds = {x: batch_xs, y: batch_ys}
# 累计计算总的损失值
avg_cost += sess.run(cost, feed_dict=feeds) / num_batch
# 输出一些数据
if epoch % display_step == 0:
# 为了输出在训练集上的正确率本来应该使用全部的train数据 这里为了快一点就只用了部分数据
feed_train = {x: trainimg[1: 100], y: trainlabels[1: 100]}
# 在测试集上运行模型
feedt_test = {x: mnist.test.images, y: mnist.test.labels}
train_acc = sess.run(accr, feed_dict=feed_train)
test_acc = sess.run(accr, feed_dict=feedt_test)
print("Eppoch: %03d/%03d cost: %.9f train_acc: %.3f test_acc: %.3f" %
(epoch, training_epochs, avg_cost, train_acc, test_acc))
print("Done.")
翻译自
https://blog.csdn.net/weixin_43159628/article/details/83241345
https://www.cnblogs.com/Ran-Chen/p/9220739.html
https://blog.csdn.net/sinat_34328764/article/details/83832487