学习心得:用python读取mnist数据集的方法

mnist手写数字数据集在机器学习中非常常见,这里记录一下用python从本地读取mnist数据集的方法。

数据集格式介绍

这部分内容网络上很常见,这里还是简明介绍一下。网络上下载的mnist数据集包含4个文件:
在这里插入图片描述
前两个分别是测试集的image和label,包含10000个样本。后两个是训练集的,包含60000个样本。.gz表示这个一个压缩包,如果进行解压的话,会得到.ubyte格式的二进制文件。
在这里插入图片描述
上图是训练集的label和image数据的存储格式。两个文件最开始都有magic number和number of images/items两个数据,有用的是第二个,表示文件中存储的样本个数。另外要注意的是数据的位数,有32位整型和8位整型两种。

读取方法

.gz格式的文件读取

需要import gzip
读取训练集的代码如下:

def load_mnist_train(path, kind='train'): 
’‘’
path:数据集的路径
kind:值为train,代表读取训练集
‘’‘   
    labels_path = os.path.join(path,'%s-labels-idx1-ubyte.gz'% kind)
    images_path = os.path.join(path,'%s-images-idx3-ubyte.gz'% kind)
    #使用gzip打开文件
    with gzip.open(labels_path, 'rb') as lbpath:
	    #使用struct.unpack方法读取前两个数据,>代表高位在前,I代表32位整型。lbpath.read(8)表示一次从文件中读取8个字节
	    #这样读到的前两个数据分别是magic number和样本个数
        magic, n = struct.unpack('>II',lbpath.read(8))
        #使用np.fromstring读取剩下的数据,lbpath.read()表示读取所有的数据
        labels = np.fromstring(lbpath.read(),dtype=np.uint8)
    with gzip.open(images_path, 'rb') as imgpath:
        magic, num, rows, cols = struct.unpack('>IIII',imgpath.read(16))
        images = np.fromstring(imgpath.read(),dtype=np.uint8).reshape(len(labels), 784)
    return images, labels

读取测试集的代码类似。

非压缩文件的读取

如果在本地对四个文件解压缩之后,得到的就是.ubyte格式的文件,这时读取的代码有所变化。

def load_mnist_train(path, kind='train'): 
’‘’
path:数据集的路径
kind:值为train,代表读取训练集
‘’‘   
    labels_path = os.path.join(path,'%s-labels-idx1-ubyte'% kind)
    images_path = os.path.join(path,'%s-images-idx3-ubyte'% kind)
    #不再用gzip打开文件
    with open(labels_path, 'rb') as lbpath:
	    #使用struct.unpack方法读取前两个数据,>代表高位在前,I代表32位整型。lbpath.read(8)表示一次从文件中读取8个字节
	    #这样读到的前两个数据分别是magic number和样本个数
        magic, n = struct.unpack('>II',lbpath.read(8))
        #使用np.fromfile读取剩下的数据
        labels = np.fromfile(lbpath,dtype=np.uint8)
    with gzip.open(images_path, 'rb') as imgpath:
        magic, num, rows, cols = struct.unpack('>IIII',imgpath.read(16))
        images = np.fromfile(imgpath,dtype=np.uint8).reshape(len(labels), 784)
    return images, labels

读取之后可以查看images和labels的长度,确认读取是否正确。

  • 10
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值