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

标签 python python-3.x gzip gunzip

我期望以下代码

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/

相关文章:

python - 如何查看网格和单元格 Python 中的内容

python - 如何获取本地时区日期时间以在 django 中进行日期比较

python - 类型错误 : Object of type ResultProxy is not JSON serializable: result in sqlalchemy query?

python - Apache 下的 webapp2(= 没有 Google App Engine)

python - 处理器 ID Python 3

python - 为什么Python的内置数学运算符在处理大数时很慢?

python-3.x - 数据框中哪一行是额外的?

c - 解压大于可用内存的gz文件

linux - 以反向管道将 gzip 文件 grep 到尾部/头部的快速方法

php curl,检测响应是否为 gzip