unpack_from 需要至少 784 字节的缓冲区

unpack_from requires a buffer of at least 784 bytes

我运行 ML 模型的以下函数。

def get_images(filename):
    bin_file = open(filename, 'rb')
    buf = bin_file.read()  # all the file are put into memory
    bin_file.close()  # release the measure of operating system
    index = 0
    magic, num_images, num_rows, num_colums = struct.unpack_from(big_endian + four_bytes, buf, index)
    index += struct.calcsize(big_endian + four_bytes)
    images = []  # temp images as tuple
    for x in range(num_images):
        
        im = struct.unpack_from(big_endian + picture_bytes, buf, index)
        index += struct.calcsize(big_endian + picture_bytes)
        im = list(im)
        for i in range(len(im)):
            if im[i] > 1:
                im[i] = 1

但是,我在以下行收到错误消息:

im = struct.unpack_from(big_endian + picture_bytes, buf, index)

出现错误:

error: unpack_from requires a buffer of at least 784 bytes

我注意到此错误仅在某些迭代中发生。我不明白为什么会这样。该数据集是标准的 MNIST 数据集,可在线免费获得。

我也查看了关于 SO 的类似问题(例如 ),但他们似乎没有解决问题。

您没有在您的 mre 中包含结构格式,所以很难说为什么会出现错误。您使用的是 partial/corrupted 文件,或者您的结构格式有误。

此答案使用测试文件 't10k-images-idx3-ubyte.gz'http://yann.lecun.com/exdb/mnist/

中的文件格式

打开文件并将其读入一个字节 object(由于文件的类型,使用了 gzip)。

import gzip,struct
with gzip.open(r'my\path\t10k-images-idx3-ubyte.gz','rb') as f:
    data = bytes(f.read())
print(len(data))

文件格式规范说 header 是 16 字节(四个 32 位整数)- 用切片将它与像素分开然后解压它

hdr,pixels = data[:16],data[16:]
magic, num_images, num_rows, num_cols = struct.unpack(">4L",hdr)
# print(len(hdr),len(pixels))
# print(magic, num_images, num_rows, num_cols)

有多种方法可以迭代单个图像。

img_size = num_rows * num_cols
imgfmt = "B"*img_size
for i in range(num_images):
    start = i * img_size
    end = start + img_size
    img = pixels[start:end]
    img = struct.unpack(imgfmt,img)
    # do work on the img

或者...

imgfmt = "B"*img_size
for img in struct.iter_unpack(imgfmt, pixels):
    img = [p if p == 0 else 1 for p in img]

itertools grouper recipe 可能也可以。