【问题标题】:Read numpy data from GZip file over the network通过网络从 GZip 文件中读取 numpy 数据
【发布时间】:2017-11-06 18:17:03
【问题描述】:

我正在尝试下载 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,这是一个似乎无法通过 Google 搜索的错误。可能是什么问题?

【问题讨论】:

    标签: python-3.x numpy gzip


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多