MNIST手写字体识别(机器学习)

练习:使用 CNN(卷积神经网络)识别 MNIST手写字体— Tensorflow

  • 本文利用卷积神经网络将 MNIST 数据集的28×28像素的灰度手写数字图片识别为相应的数字。

  • mnist有六万多张手写数字的图片,每个图片用28x28的像素矩阵表示。所以我们的输入层每个案列的特征个数就有28x28=784个;因为数字有0,1,2…9共十个,所以我们的输出层是个1x10的向量。输出层是十个小于1的非负数,表示该预测是0,1,2…9的概率,我们选取最大概率所对应的数字作为我们的最终预测。

  • 首先导入库

    import numpy as np
    import pandas as pd
    import tensorflow as tf
    
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    
    tf.logging.set_verbosity(tf.logging.ERROR)
    # 由于版本问题,可以忽略 tensor 的警告
    
  • 然后导入数据集,并对参数进行设置

    # 设置
    Learning_rate = 1e-4                    # 学习率
    Training_iterations = 2500              # 迭代次数
    Dropout = 0.5                           # 每次杀死50%的神经元,防止过拟合
    Batch_size = 50                         # 每次迭代50张图像
    Validation_size = 2000                  # 验证集
    Image_to_display = 10                   # 输出10种类型
    
    # 读取训练集
    data = pd.read_csv('mnist_train.csv')
    
    print('data({0[0]}, {0[1]})'.format(data.shape))
    print(data.head())
    

运行结果为:
  • 对数据进行处理,得到图像的像素、宽度和高度

    # 数据简单预处理
    images = data.iloc[:,1:].values
    images = images.astype(np.float)
    images = np.multiply(images, 1.0 / 255.0)       # 归一化数据
    
    print('images({0[0]}, {0[1]})'.format(images.shape))
    
    # 图像像素
    image_size = images.shape[1]
    print('image_size => {0}'.format(image_size))
    
    # 图像的宽和高
    image_width = image_height = np.ceil(np.sqrt(image_size)).astype(np.uint8)
    print('image_width => {0}\nimage_height => {1}'.format(image_width, image_height))
    

运行结果为:
  • 查看当前图片

     def display(img):
          one_image = img.reshape(image_width, image_height)     # 转换图像格式
          plt.axis('off')
          plt.imshow(one_image, cmap=cm.binary)
          plt.show()
    
    display(images[Image_to_display])
    

运行结果为:

从图中可以看出,有可能数字5,或者数字6

  • 查看实际对应的数字

    # 查看 label
    labels_flat = data.iloc[:,0].values.ravel()
    
    print('labels_flat({0})'.format(len(labels_flat)))
    print('labels_flat[{0}] => {1}'.format(Image_to_display, labels_flat[Image_to_display]))
    
    labels_count = np.unique(labels_flat).shape[0]
    
    print('labels_count => {0}'.format(labels_count))
    

运行结果为:

从运行结果来看,图片的数字为5。

  • 然后对数据进行 one-hot 编码处理

     # 对数据进行 one-hot 编码
    # 0 => [1 0 0 0 0 0 0 0 0 0]
    # 1 => [0 1 0 0 0 0 0 0 0 0]
    # ...
    # 9 => [0 0 0 0 0 0 0 0 0 1]
    def dense_to_one_hot(labels_dense, num_classes):
    
        num_labels = labels_dense.shape[0]
        index_offset = np.arange(num_labels) * num_classes
        labels_one_hot = np.zeros((num_labels, num_classes))
    
        # flat就是相当于变成一维数组,再读取
        # ravel将多维数组转化为一维,返回一个连续的平整的数组。
        labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
        return labels_one_hot
    
    labels = dense_to_one_hot(labels_flat, labels_count)
    labels = labels.astype(np.uint8)
    
    # print('labels({0[0]}, {0[1]})'.format(labels.shape))
    # print('labels[{0}] => {1}'.format(Image_to_display, labels[Image_to_display]))
    
  • 我们还需要把训练数据划分出一个验证集,来证明我们所做的模型是否有泛化能力。

    # 数据集的切分
    validation_images = images[:2000]
    validation_labels = labels[:2000]
    
    train_images = images[2000:]
    train_labels = labels[2000:]
    
    print('train_images({0[0]}, {0[1]})'.format(train_images.shape))
    print('train_labels({0[0]}, {0[1]})'.format(train_labels.shape))
    

运行结果为:
  • 接下来就是构建Tensorflow图,我们想要构建两个卷积层,所以要对权值W进行初始化。而且我们选Relu作为我们的激活函数。由于Relu的特性,容易产生“死”的神经元,所以我们初始化偏置为较小的整数。

    # 建立神经网络
    # 权重初始化
    def weight_variable(shape):
        # 注:tensor 需要初始化,需要将数据转换为 tensor 支持的格式
        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)
    
  • 我们选择0补充层来防止数据宽高减小。步长选择为1。

    # 补充层
    def con2d(x, W):
        # x 指输入;W 指CNN的卷积核;strides 卷积时在图像上每一维的步长,一般首尾为1,中间为自定义的步长
        return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
    
  • 定义池化,池化作用有:
    1.保持不变性,比如两张图有平移,旋转,尺度时,通过取最大值(maxpooling)可以使标签相同但是图像略微不同的图具有相同的特征。
    2.保留主要特征同时减少参数和计算量,防止过拟合,提高模型的泛化能力。

    # 池化
    def max_pool_2x2(x):
        # x 指池化输入,ksize 为池化窗口的大小,strides 为窗口在每一个维度上滑动的步长
        return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    
  • 定义占位符

    # 定义占位符
    x = tf.placeholder(tf.float32, shape=[None, image_size])
    y_ = tf.placeholder(tf.float32, shape=[None, labels_count])
    
  • 定义第一层神经网络,第一层神经网络用了5*5的过滤器,并且卷积层想要预估出32个特征值,我们可以得出权重的shape[5, 5, 1, 32].这里第三个数字是输入的通道要与上一层的输出通道值相一致。

    # 第一层卷积神经网络,选择一个5*5的窗口,初始图像为28*28*1,将图像分为32个特征图
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    
    image = tf.reshape(x, [-1, image_width, image_height, 1])
    # print(image.get_shape())
    
    h_conv1 = tf.nn.relu(con2d(image, W_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)
    # print(h_conv1.get_shape())
    # print(h_pool1.get_shape())
    
  • 定义第二层神经网络,第二层卷积层想要预估出64个特征值,得到权重的shape[5, 5, 32, 64]。因为经过池化层,图像已经变成了14*14的大小,第二层卷几层想要得到更一般的特征,过滤器覆盖了图像的更多空间,所以我们调整选择使用更多的特征。

    # 第二层卷积神经网络
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    
    h_conv2 = tf.nn.relu(con2d(h_pool1, W_conv2) + b_conv2)
    h_pool2 = max_pool_2x2(h_conv2)
    # print(h_conv2.get_shape())
    # print(h_pool2.get_shape())
    
  • 定义全连接层

    # 定义全连接层
    W_fc1 = weight_variable([7*7*64, 1024])
    b_fc1 = bias_variable([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)
    # print(h_pool2_flat.get_shape())
    # print(h_fc1.get_shape())
    
  • 防止过拟合,加入了随机失活。

    # 防止过拟合,随机杀死一些神经元
    keep_prob = tf.placeholder('float')                     # 保存率
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
    
  • 最后使用softmax来得到各分类的预测分数。

    W_fc2 = weight_variable([1024, labels_count])
    b_fc2 = bias_variable([labels_count])
    
    # 使用softmax来得到各分类的预测分数
    y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
    # print(y.get_shape())
    
  • 为了使用反向传播来更新权值,我们需要定义损失函数,这里我们使用了交叉熵。还需要定义一个优化方法,选择了Adam算法。

    # 损失函数,这里使用了交叉熵
    cross_entropy = -tf.reduce_sum(y_*tf.log(y))
    
    # 优化函数
    train_step = tf.train.AdamOptimizer(Learning_rate).minimize(cross_entropy)
    
    # 评估
    correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
    
  • 最后预测属于哪个数字。

    # 预测函数
    predict = tf.argmax(y,1)
    
  • 训练,验证,预测

    # 训练,验证,预测
    epochs_completed = 0
    index_in_epoch = 0
    num_examples = train_images.shape[0]
    
    # 按 batch 迭代数据
    def next_batch(batch_size):
        global train_images
        global train_labels
        global index_in_epoch
        global epochs_completed
    
        start = index_in_epoch
        index_in_epoch += batch_size
    
        # 当所有训练数据都已被使用时,它会被随机重新排序
        if index_in_epoch > num_examples:
    
            epochs_completed += 1
    
            # 冲洗数据
            perm = np.arange(num_examples)
            np.random.shuffle(perm)
    
            train_images = train_images[perm]
            train_labels = train_labels[perm]
    
            start = 0
            index_in_epoch = batch_size
            assert batch_size <= num_examples
        end = index_in_epoch
        return train_images[start:end], train_labels[start:end]
    
  • 做好上面工作后,我们可以启动tensorflow,这一步绝对不能少。

    init = tf.initialize_all_variables()
    sess = tf.InteractiveSession()
    sess.run(init)
    
  • 接下来,开始训练。

    # 变量可视化
    train_accuracies = []
    validation_accuracies = []
    x_range = []
    display_step = 1
    
    # 迭代多次,需要 next_batch
    for i in range(Training_iterations):
    
        # 获得新的批次
        batch_xs, batch_ys = next_batch(Batch_size)
    
        # 判断每一步的进度
        if i%display_step == 0 or (i+1) == Training_iterations:
    
            # 传入 x,y_
            train_accuracy = accuracy.eval(feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 1.0})
    
            if (Validation_size):
                validation_accuracy = accuracy.eval(feed_dict={x: validation_images[0: Batch_size],
                                                         y_: validation_labels[0: Batch_size],
                                                         keep_prob: 1.0})
    
                print('train_accuracy / validation_accuracy => %.2f / %.2f for step %d'%(train_accuracy,
                                                                          validation_accuracy, i))
                validation_accuracies.append(validation_accuracy)
    
            else:
                print('training_accuracy => %.4f for step %d'%(train_accuracy, i))
    
            train_accuracies.append(train_accuracy)
            x_range.append(i)
    
            # 增加显示步骤
            if i%(display_step*10) ==0 and i:
                display_step *= 10
    
        # 批量训练
        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: Dropout})
    

运行结果为:

从图中可以看出训练的结果准确率大概只有98%。

  • 用matplotlib画出train和validation的准确度。

    # 检测 train 和 validation 的准确度
    if (Validation_size):
        validation_accuracy = accuracy.eval(feed_dict = {x: validation_images,
                                                   y_: validation_labels,
                                                   keep_prob:1.0})
    
        plt.plot(x_range, train_accuracies, '-b', label='Training')
        plt.plot(x_range, validation_accuracies, '-g', label='Validation')
    
        plt.legend(loc='lower right', frameon=False)
        plt.ylim(top=1.1, bottom=0.7)
    
        plt.ylabel('accuracy')
        plt.xlabel('step')
        plt.show()
    

运行结果为:
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容