使用神经网络对手写数字进行分类
学习目标:
- 训练线性模型和神经网络,以对传统 MNIST 数据集中的手写数字进行分类
- 比较线性分类模型和神经网络分类模型的效果
- 可视化神经网络隐藏层的权重
我们的目标是将每个输入图片与正确的数字相对应。我们会创建一个包含几个隐藏层的神经网络,并在顶部放置一个归一化指数层,以选出最合适的类别。
第1步:设置:加载必要的库+加载数据+数据预处理
from __future__ import print_function
import glob
import math
import os
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.logging.set_verbosity(tf.logging.ERROR)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format
mnist_dataframe = pd.read_csv(
"https://download.mlcc.google.com/mledu-datasets/mnist_train_small.csv",
sep=",",
header=None)
# Use just the first 10,000 records for training/validation
mnist_dataframe = mnist_dataframe.head(10000)
mnist_dataframe = mnist_dataframe.reindex(np.random.permutation(mnist_dataframe.index))
mnist_dataframe.head()
第一列中包含类别标签。其余列中包含特征值,每个像素对应一个特征值,有 28×28=784
个像素值,其中大部分像素值都为零;您也许需要花一分钟时间来确认它们不全部为零。
这些样本都是分辨率相对较低、对比度相对较高的手写数字图片。0-9
这十个数字中的每个可能出现的数字均由唯一的类别标签表示。因此,这是一个具有 10 个类别的多类别分类问题。
现在,我们解析一下标签和特征,并查看几个样本。注意 loc
的使用,借助 loc
,我们能够基于原来的位置抽出各列,因为此数据集中没有标题行。
def parse_labels_and_features(dataset):
"""Extracts labels and features.
This is a good place to scale or transform the features if needed.
Args:
dataset: A Pandas `Dataframe`, containing the label on the first column and
monochrome pixel values on the remaining columns, in row major order.
Returns:
A `tuple` `(labels, features)`:
labels: A Pandas `Series`.
features: A Pandas `DataFrame`.
"""
labels = dataset[0] #数据的第0列为标签列
# DataFrame.loc index ranges are inclusive at both ends.
features = dataset.loc[:,1:784] #数据第1~784行为数据内容列
# Scale the data to [0, 1] by dividing out the max value, 255.
features = features / 255 #通过除以255把特征值缩小到[0,1]之间
return labels, features
预览数据集:
training_targets, training_examples = parse_labels_and_features(mnist_dataframe[:7500])
training_examples.describe()
第2步:样本特征列的选择
rand_example = np.random.choice(training_examples.index)
_, ax = plt.subplots()
ax.matshow(training_examples.loc[rand_example].values.reshape(28, 28))
ax.set_title("Label: %i" % training_targets.loc[rand_example])
ax.grid(False)
第三步:样本特征列的选择
def construct_feature_columns():
"""Construct the TensorFlow Feature Columns.
Returns:
A set of feature columns
"""
# There are 784 pixels in each image
return set([tf.feature_column.numeric_column('pixels', shape=784)])
*对比示范第3步*:为 MNIST 构建线性模型
在本次练习中,我们会对训练和预测使用单独的输入函数,并将这些函数分别嵌套在 create_training_input_fn()
和 create_predict_input_fn()
中,这样一来,我们就可以调用这些函数,以返回相应的 _input_fn
,并将其传递到 .train()
和 .predict()
调用。
def create_training_input_fn(features, labels,