代码之家  ›  专栏  ›  技术社区  ›  oarfish

通过网络从GZip文件读取numpy数据

  •  0
  • oarfish  · 技术社区  · 7 年前

    我正在尝试下载 MNIST 数据集并解码,而无需将其写入磁盘(主要是为了好玩)。

    request_stream = urlopen('http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz')
    zip_file = GzipFile(fileobj=request_stream, mode='rb')
    with zip_file as fd:
        magic, numberOfItems = struct.unpack('>ii', fd.read(8))
        rows, cols = struct.unpack('>II', fd.read(8))
        images = np.fromfile(fd, dtype='uint8') # < here be dragons
        images = images.reshape((numberOfItems, rows, cols))
        return images
    

    此代码失败 OSError: obtaining file position failed ,这似乎是一个无法识别的错误。问题可能是什么?

    1 回复  |  直到 7 年前
        1
  •  0
  •   oarfish    7 年前

    问题 seems to be 那是什么 gzip 而类似的模块提供的并不是真正的文件对象(不足为奇),但是 numpy 试图通读实际 FILE* 指针,所以这无法工作。

    如果可以将整个文件读入内存(可能不是),那么可以通过将所有非头信息读入 bytearray 从中反序列化:

    rows, cols = struct.unpack('>II', fd.read(8))
    b = bytearray(fd.read())
    images = np.frombuffer(b, dtype='uint8')
    images = images.reshape((numberOfItems, rows, cols))
    return images