程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

【Python机器学习及实践】实战篇:MNIST手写体数字图片识别

发布于2019-08-20 15:00     阅读(972)     评论(0)     点赞(6)     收藏(5)


Python机器学习及实践——实战篇:MNIST手写体数字图片识别

作为kaggle上入门级别比赛,手写体数字识别是最基本的一个。这里所用的数据为MNIST提供的0-9的手写体数字,kaggle上提供了csv格式的数据文件,可以直接读取。这里推荐使用readr包的read_csv函数读取,能够进一步提升文件读取速度。

数据简介:训练集样本个数为42000,测试集样本个数为28000,第一列为label为标签,第2到第785列为黑白图片每个像素点的灰度值(28*28).

模型搭建:采用多种基于skflow工具包的模型完成大规模手写体数字图片识别的任务。这些模型包括:线性回归器,全连接并包含三个隐层的深度神经网络(DNN)以及一个较为复杂但是性能强大的卷积神经网络(CNN)。

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. @File : MNIST.py
  5. @Author: Xinzhe.Pang
  6. @Date : 2019/7/28 0:27
  7. @Desc :
  8. """
  9. import pandas as pd
  10. train = pd.read_csv('./train.csv')
  11. # 查看训练样本信息
  12. print(train.shape)
  13. # 使用pandas从本地读取的MNIST手写体数字测试图片集
  14. test = pd.read_csv('./test.csv')
  15. print(test.shape)
  16. # 将训练集中的数据特征与对应标记分离
  17. y_train = train['label']
  18. X_train = train.drop('label', 1)
  19. # 准备测试特征
  20. X_test = test
  21. # 分别导入tensorflow和skflow
  22. import tensorflow as tf
  23. import skflow
  24. # 使用skflow中已经封装好的基于tensorflow搭建的线性分类器TensorflowFlowLinearClassifier进行学习预测
  25. classifier = skflow.TensorFlowLinearClassifier(n_classes=10, batch_size=100, steps=1000, learning_rate=0.01)
  26. classifier.fit(X_train, y_train)
  27. linear_y_pred = classifier.predict(X_test)
  28. linear_submission = pd.DataFrame({'ImageId': range(1, 28001), 'Label': linear_y_pred})
  29. linear_submission.to_csv('./linear_submission.csv', index=False)
  30. # 使用基于tensorflow搭建的全连接深度神经网络TensorflowDNNClassifier进行学习预测
  31. classifier = skflow.TensorFlowDNNClassifier(hidden_units=[200, 50, 10], n_classes=10, steps=5000, learning_rate=0.01,
  32. batch_size=50)
  33. classifier.fit(X_train, y_train)
  34. dnn_y_pred = classifier.predict(X_test)
  35. dnn_submission = pd.DataFrame({'ImageId': range(1, 28001), 'Label': dnn_y_pred})
  36. dnn_submission.to_csv('./dnn_submission.csv', index=False)
  37. # 使用Tensorflow中的算子自行搭建更为复杂的卷积神经网络,并使用skflow的程序接口从事MNIST数据的学习与预测
  38. def max_pool_2x2(tensor_in):
  39. return tf.nn.max_pool(tensor_in, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  40. def conv_model(X, y):
  41. X = tf.reshape(X, [-1, 28, 28, 1])
  42. with tf.variable_scope('conv_layer1'):
  43. h_conv1 = skflow.ops.conv2d(X, n_filters=32, filter_shape=[5, 5], bias=True, activation=tf.nn.relu)
  44. h_pool1 = max_pool_2x2(h_conv1)
  45. with tf.variable_scope('conv_layer2'):
  46. h_conv2 = skflow.ops.conv2d(h_pool1, n_filters=64, filter_shape=[5, 5], bias=True, activation=tf.nn.relu)
  47. h_pool2 = max_pool_2x2(h_conv2)
  48. h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
  49. h_fcl = skflow.ops.dnn(h_pool2_flat, [1024], activation=tf.nn.relu, keep_prob=0.5)
  50. return skflow.models.logistic_regression(h_fcl, y)
  51. classifier = skflow.TensorFlowEstimator(model_fn=conv_model, n_classes=10, batch_size=100, steps=20000,
  52. learning_rate=0.001)
  53. classifier.fit(X_train, y_train)
  54. # 这里不要直接将所有测试样本交给模型进行预测,因为Tensorflow会同时对所有测试样本进行矩阵运算,一次对28000个测试图片进行计算
  55. # 会消耗大量的内存和计算资源,这里采用的是逐批次地对样本进行预测,最后拼接全部预测结果
  56. conv_y_pred = []
  57. import numpy as np
  58. for i in np.arange(100, 28001, 100):
  59. conv_y_pred = np.append(conv_y_pred, classifier.predict(X_test[i - 100:i]))
  60. conv_submission = pd.DataFrame({'ImageId': range(1, 28001), 'Label': np.int32(conv_y_pred)})
  61. conv_submission.to_csv('./conv_submission.csv', index=False)

 



所属网站分类: 技术文章 > 博客

作者:雷神归来

链接:https://www.pythonheidong.com/blog/article/49450/8d412d6da4157d41f647/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

6 0
收藏该文
已收藏

评论内容:(最多支持255个字符)