python idx是什么_使用Python解析MNIST数据集(IDX文件格式)

本文介绍了如何使用Python解析MNIST数据集的IDX文件格式,包括IDX文件的基本结构、解析规则,并提供了具体的Python解析脚本,通过struct模块读取和处理IDX文件,将数据转换为numpy数组。
摘要由CSDN通过智能技术生成

前言

最近在学习Keras,要使用到LeCun大神的MNIST手写数字数据集,直接从官网上下载了4个压缩包:

MNIST数据集

解压后发现里面每个压缩包里有一个idx-ubyte文件,没有图片文件在里面。回去仔细看了一下官网后发现原来这是IDX文件格式,是一种用来存储向量与多维度矩阵的文件格式。

IDX文件格式

官网上的介绍如下:

THE IDX FILE FORMAT

the IDX file format is a simple format for vectors and multidimensional matrices of various numerical types.

The basic format is

magic number

size in dimension 0

size in dimension 1

size in dimension 2

.....

size in dimension N

data

The magic number is an integer (MSB first). The first 2 bytes are always 0.

The third byte codes the type of the data:

0x08: unsigned byte

0x09: signed byte

0x0B: short (2 bytes)

0x0C: int (4 bytes)

0x0D: float (4 bytes)

0x0E: double (8 bytes)

The 4-th byte codes the number of dimensions of the vector/matrix: 1 for vectors, 2 for matrices....

The sizes in each dimension are 4-byte integers (MSB first, high endian, like in most non-Intel processors).

The data is stored like in a C array, i.e. the index in the last dimension changes the fastest.

解析脚本

根据以上解析规则,我使用了Python里的struct模块对文件进行读写(如果不熟悉struct模块的可以看我的另一篇博客文章《Python中对字节流/二进制流的操作:struct模块简易使用教程》)。IDX文件的解析通用接口如下:

# 解析idx1格式

def decode_idx1_ubyte(idx1_ubyte_file):

"""

解析idx1文件的通用函数

:param idx1_ubyte_file: idx1文件路径

:return: np.array类型对象

"""

return data

def decode_idx3_ubyte(idx3_ubyte_file):

"""

解析idx3文件的通用函数

:param idx3_ubyte_file: idx3文件路径

:return: np.array类型对象

"""

return data

针对MNIST数据集的解析脚本如下

# encoding: utf-8

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值