python MNIST手写识别数据调用API的方法

yipeiwu_com5年前Python基础

MNIST数据集比较小,一般入门机器学习都会采用这个数据集来训练

下载地址:yann.lecun.com/exdb/mnist/

有4个有用的文件:
train-images-idx3-ubyte: training set images
train-labels-idx1-ubyte: training set labels
t10k-images-idx3-ubyte: test set images
t10k-labels-idx1-ubyte: test set labels

The training set contains 60000 examples, and the test set 10000 examples. 数据集存储是用binary file存储的,黑白图片。

下面给出load数据集的代码:

import os
import struct
import numpy as np
import matplotlib.pyplot as plt

def load_mnist():
  '''
  Load mnist data
  http://yann.lecun.com/exdb/mnist/

  60000 training examples
  10000 test sets

  Arguments:
    kind: 'train' or 'test', string charater input with a default value 'train'

  Return:
    xxx_images: n*m array, n is the sample count, m is the feature number which is 28*28
    xxx_labels: class labels for each image, (0-9)
  '''

  root_path = '/home/cc/deep_learning/data_sets/mnist'

  train_labels_path = os.path.join(root_path, 'train-labels.idx1-ubyte')
  train_images_path = os.path.join(root_path, 'train-images.idx3-ubyte')

  test_labels_path = os.path.join(root_path, 't10k-labels.idx1-ubyte')
  test_images_path = os.path.join(root_path, 't10k-images.idx3-ubyte')

  with open(train_labels_path, 'rb') as lpath:
    # '>' denotes bigedian
    # 'I' denotes unsigned char
    magic, n = struct.unpack('>II', lpath.read(8))
    #loaded = np.fromfile(lpath, dtype = np.uint8)
    train_labels = np.fromfile(lpath, dtype = np.uint8).astype(np.float)

  with open(train_images_path, 'rb') as ipath:
    magic, num, rows, cols = struct.unpack('>IIII', ipath.read(16))
    loaded = np.fromfile(train_images_path, dtype = np.uint8)
    # images start from the 16th bytes
    train_images = loaded[16:].reshape(len(train_labels), 784).astype(np.float)

  with open(test_labels_path, 'rb') as lpath:
    # '>' denotes bigedian
    # 'I' denotes unsigned char
    magic, n = struct.unpack('>II', lpath.read(8))
    #loaded = np.fromfile(lpath, dtype = np.uint8)
    test_labels = np.fromfile(lpath, dtype = np.uint8).astype(np.float)

  with open(test_images_path, 'rb') as ipath:
    magic, num, rows, cols = struct.unpack('>IIII', ipath.read(16))
    loaded = np.fromfile(test_images_path, dtype = np.uint8)
    # images start from the 16th bytes
    test_images = loaded[16:].reshape(len(test_labels), 784)  

  return train_images, train_labels, test_images, test_labels

再看看图片集是什么样的:

def test_mnist_data():
  '''
  Just to check the data

  Argument:
    none

  Return:
    none
  '''
  train_images, train_labels, test_images, test_labels = load_mnist()
  fig, ax = plt.subplots(nrows = 2, ncols = 5, sharex = True, sharey = True)
  ax =ax.flatten()
  for i in range(10):
    img = train_images[i][:].reshape(28, 28)
    ax[i].imshow(img, cmap = 'Greys', interpolation = 'nearest')
    print('corresponding labels = %d' %train_labels[i])

if __name__ == '__main__':
  test_mnist_data()

跑出的结果如下:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

解决PyCharm不运行脚本,而是运行单元测试的问题

解决方案: 1、选择Edit Configurations, 删除相关单元测试 2、右击__name__ == "__main__",点击运行即可。 以上这篇解决PyCharm不运行脚本...

Python输出汉字字库及将文字转换为图片的方法

Python输出汉字字库及将文字转换为图片的方法

用python输出汉字字库 问题1:假设我们知道汉字编码范围是0x4E00到0x9FA5,怎么从十六进制的编码转成人类可读的字呢? 问题2:怎么把unicode编码的字写入文件呢,如果直...

python中有关时间日期格式转换问题

python中有关时间日期格式转换问题

每次遇到pandas的dataframe某列日期格式问题总会哉坑,下面记录一下常用时间日期函数.... 1、字符串转化为日期 str—>date import datetime...

python消费kafka数据批量插入到es的方法

1、es的批量插入 这是为了方便后期配置的更改,把配置信息放在logging.conf中 用elasticsearch来实现批量操作,先安装依赖包,sudo pip install El...

Python读取ini文件、操作mysql、发送邮件实例

我是闲的没事干,2014过的太浮夸了,博客也没写几篇,哎~~~ 用这篇来记录即将逝去的2014 python对各种数据库的各种操作满大街都是,不过,我还是喜欢我这种风格的,涉及到其它操作...