gpt4 book ai didi

Python gzip 模块在 ubyte 文件上无法按预期工作

转载 作者:行者123 更新时间:2023-11-30 22:25:18 27 4
gpt4 key购买 nike

我期望以下代码

import gzip
import numpy as np

def read_ubyte(self, fname):
with gzip.open(fname, 'rb') as flbl:
magic, num = struct.unpack(">II", flbl.read(8))
lbl = np.fromfile(flbl, dtype=np.int8)
return magic, num, lbl

if __name__ == "__main__":
print(read_ubyte("train-labels-idx1-ubyte.gz"))

与先执行gunzip train-labels-idx1-ubyte.gz然后执行的工作方式完全相同

import numpy as np

def read_ubyte(self, fname):
with open(fname, 'rb') as flbl:
magic, num = struct.unpack(">II", flbl.read(8))
lbl = np.fromfile(flbl, dtype=np.int8)
return magic, num, lbl

if __name__ == "__main__":
print(read_ubyte("train-labels-idx1-ubyte"))

但事实并非如此,第一个代码给出了输出:

(2049, 60000, array([  0,   3, 116, ..., -22,   0,   0], dtype=int8))

第二个

(2049, 60000, array([5, 0, 4, ..., 5, 6, 8], dtype=int8))

为什么?

注 1:第二个是正确的输出(没有使用 gzip 模块)

注2:数字2049和60000是正确的

注3:如果您想重现,可以在 http://yann.lecun.com/exdb/mnist/ 下载文件

最佳答案

NumPy 和 GZip 在文件对象语义方面存在分歧。这是known issue ,NumPy 的某些部分(例如 np.load())可以容纳,但 fromfile() 不能。

要解决这个问题(仅在 gzip 情况下需要,但在两者中都适用):

    lbl = np.fromstring(flbl.read(), dtype=np.int8)

关于Python gzip 模块在 ubyte 文件上无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47574607/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com