如何将Mnist数据集(idx格式)正确解析为python数组



我是机器学习的新手,每次我需要处理数据集时,我都尽量避免从openml模块下载mnist数据集。我在网上看到了这段代码,它帮助我将idx文件转换为python数组,但我的train_set标签一直缺少8个值,我认为这与我转换它的方式有关。

import numpy as np
import struct
with open('train-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))
with open('train-labels.idx1-ubyte', 'rb') as i:
magic, size = struct.unpack('>II', i.read(8))
nrows, ncols = struct.unpack('>II', i.read(8))
data_1 = np.fromfile(i, dtype=np.dtype(np.uint8)).newbyteorder(">")    

x_train, y_train = data, data_1
len(x_train), len(y_train)
>>> (60000,59992)

如上面的代码所示,这个问题使我的标签变得有问题,因为不是所有的火车图像都能正确链接。我已经尝试了多次下载该文件,以确保我没有获得损坏的文件。求你了,我需要帮助。感谢

检查文档

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
The labels values are 0 to 9.

前4个字节是神奇的数字,接下来是4个项目数。之后标签开始。所以你必须跳过8个字节才能到达lables。但是你跳过了16个字节,跳过了几个标签。

修复

with open('train-labels.idx1-ubyte', 'rb') as i:
magic, size = struct.unpack('>II', i.read(8))
data_1 = np.fromfile(i, dtype=np.dtype(np.uint8)).newbyteorder(">")   

最新更新