首页 > 解决方案 > 如何读取 QMnist 标签文件?

问题描述

QMnist 标签文件与 MNIST 数据集标签文件略有不同。qmnist-train-labels-idx2-int.gz 是 2D 张量,但我无法解码标签文件以提取类标签。

    f = gzip.open('./QMnist/qmnist-train-labels-idx2-int.gz','r')
    f.read(12)# skip 12 byte as document says
    buf = f.read()
    datalabel = np.frombuffer(buf, dtype=np.uint32).astype(np.int32)
    datalabel = datalabel.reshape(8,num_images)
    print(datalabel[0])

结果在某种程度上是正确的,但仍然有问题:

[ 83886080 67108864 1778909184 ...,-1525809152 0 0]

最后 2 项是 0,这是正确的(第 6 项:重复 = 0,第 7 项:未使用 = 0)。但是,第一项是错误的!我无法将其与数字 5 联系起来。

标签: pythondeep-learningmnist

解决方案


中的函数read_idx2_int就是qmnist.py这样做的。

import codecs

def get_int(b):
    return int(codecs.encode(b, 'hex'), 16)

def open_maybe_compressed_file(path):
    if path.endswith('.gz'):
        return gzip.open(path, 'rb')
    elif path.endswith('.xz'):
        return lzma.open(path, 'rb')
    else:
        return open(path,'rb')
    
def read_idx2_int(path):
    with open_maybe_compressed_file(path) as f:
        data = f.read()
        assert get_int(data[:4]) == 12*256 + 2
        length = get_int(data[4:8])
        width = get_int(data[8:12])
        parsed = np.frombuffer(data, dtype=np.dtype('>i4'), offset=12)
        return torch.from_numpy(parsed.astype('i4')).view(length,width).long()

有关读取 mnist 文件的更通用方法,请参阅read_sn3_pascalvincent_tensor.torchvision/mnist.py


推荐阅读