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

我是机器学习的新手,我试图避免每次需要处理数据集时从openml模块下载mnist数据集。我在网上看到了一段代码,帮助我将idx文件转换为Python数组,但我在训练集标签上遇到了问题,标签总是少了8个值,我认为这与我的转换方式有关。

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)

如上面的代码所示,这个问题使得我的标签出现了错误,因为并非所有训练图像都能正确链接。我已经尝试多次下载文件以确保我没有获得损坏的文件。请帮帮我,谢谢。


回答:

查看文档

训练集标签文件 (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
标签值为0到9。

前4个字节是魔术数字,接下来的4个字节是项目数量。之后是标签。所以你需要跳过8个字节才能到达标签。但你跳过了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(">")

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注