解析 Yann LeCun 的 MNIST IDX 文件格式

2023-12-25

我想了解一下如何打开此版本的 MNIST 数据集 http://yann.lecun.com/exdb/mnist/。例如训练集标签文件train-labels-idx1-ubyte定义为:

TRAINING SET LABEL FILE (train-labels-idx1-ubyte):
[offset] [type]          [value]          [description]
0000     32 bit integer  0x00000801(2049) magic number (MSB first)
0004     32 bit integer  60000            number of items
0008     unsigned byte   ??               label
0009     unsigned byte   ??               label
........
xxxx     unsigned byte   ??               label

我在网上找到了一些代码似乎可以工作,但不明白它是如何工作的:

with open('train-labels-idx1-ubyte', 'rb') as f:
    bytes = f.read(8)
    magic, size = struct.unpack(">II", bytes)

print(magic) # 2049
print(size)  # 60000

我的理解是struct.unpack将第二个参数解释为两个 4 字节整数的大端字节字符串(请参阅here https://docs.python.org/3/library/struct.html)。当我实际打印的值bytes不过,我得到:

b'\x00\x00\x08\x01\x00\x00\xea`'

第一个四字节整数有意义:

b'\x00\x00\x08\x01'

前两个字节为 0。接下来表示数据为无符号字节。和0x01表示标签的一维向量。假设到目前为止我的理解是正确的,接下来的三个(四个?)字节发生了什么:

...\x00\x00\xea`

这如何转化为 60,000?


我编写了以下代码,以防有人需要解析整个图像数据集(如问题标题中所示),而不仅仅是前两个字节。

import numpy as np
import struct

with open('samples/t10k-images-idx3-ubyte','rb') as f:
    magic, size = struct.unpack(">II", f.read(8))
    nrows, ncols = struct.unpack(">II", f.read(8))
    data = np.fromfile(f, dtype=np.dtype(np.uint8).newbyteorder('>'))
    data = data.reshape((size, nrows, ncols))

这假设您解压缩了.gz文件。您还可以使用压缩文件,如下所示马克托迪斯科的回答 https://stackoverflow.com/a/68875266/3671939, 通过增加import gzip, using gzip.open(...)代替open(...),并使用np.frombuffer(f.read(), ...)代替np.fromfile(f, ...).

只是为了检查,显示第一个数字。就我而言,它是 7。

import matplotlib.pyplot as plt
plt.imshow(data[0,:,:], cmap='gray')
plt.show()

另外,下面的代码读取带标签的文件

with open('samples/t10k-labels-idx1-ubyte','rb') as f:
    magic, size = struct.unpack(">II", f.read(8))
    data = np.fromfile(f, dtype=np.dtype(np.uint8).newbyteorder('>'))
    data = data.reshape((size,)) # (Optional)
print(data)
# Prints: [7 2 1 ... 4 5 6]

最后一次重塑可以是(size,) or (1, size)取决于你的标准。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

解析 Yann LeCun 的 MNIST IDX 文件格式 的相关文章

随机推荐