【问题标题】:Python gzip module doesn't work as expected on ubyte filePython gzip 模块在 ubyte 文件上无法按预期工作
【发布时间】:2017-11-30 13:26:46
【问题描述】:

我期待下面的代码

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/下载文件

【问题讨论】:

    标签: python python-3.x gzip gunzip


    【解决方案1】:

    NumPy 和 GZip 在文件对象语义上存在分歧。这是一个known issue,NumPy 的某些部分(如np.load())可以容纳,但fromfile() 没有。

    要解决它(仅在 gzip 情况下需要,但两者都适用):

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-21
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2013-08-18
      相关资源
      最近更新 更多