我想了解如何打开this version of the MNIST data set。例如,训练集标签文件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字节整数的big-endian字节字符串(请参阅here)。但是,当我实际打印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))

只是检查一下,请显示第一个数字。以我为例,它是7。
import matplotlib.pyplot as plt
plt.imshow(data[0,:,:], cmap='gray')
plt.show()

python - 解析Yann LeCun的MNIST IDX文件格式-LMLPHP

关于python - 解析Yann LeCun的MNIST IDX文件格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39969045/

10-11 01:10