Python读取MNIST文件

来源:互联网 发布:如何提高淘宝店铺流量 编辑:程序博客网 时间:2024/05/21 16:54

MNIST

MNIST是LeCun的手写数字图像库,有四个文件,移步这里下载:http://yann.lecun.com/exdb/mnist/。文件格式该页有详细介绍。

Python-mnist

Sorki写了一个python的package,https://github.com/sorki/python-mnist ,我把他核心部分抄在这里。

这个是标签文件的读取方法:

import structfrom array import arraywith open("train-labels-idx1-ubyte", "rb") as f:    magic, size = struct.unpack(">II", f.read(8))    labels = array("B", f.read())    print magic, size, labels

这个是图片文件的读取方法(ipython下):

import structfrom array import arraywith open("t10k-images-idx3-ubyte", "rb") as f:    magic, size, rows, cols = struct.unpack(">IIII", f.read(16))    print magic, size, rows, cols    image_data = array("B", f.read())    images = []    for i in range(size):        images.append([0] * rows * cols)    for i in range(size):        images[i][:] = image_data[i * rows * cols:(i + 1) * rows * cols]

显示前72幅图片:

import numpy as npfrom PIL import Imageimport matplotlib.pyplot as plt%matplotlib inlinefor i,img in enumerate(images):    if i < 72:        plt.subplot(9,8,i+1)        img = np.array(img)        img = img.reshape(rows,cols)        img = Image.fromarray(img)        plt.imshow(img, cmap='gray')        plt.axis("off")    else:        break
0 0
原创粉丝点击