python - 如何读取 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 联系起来。
解决方案
中的函数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
推荐阅读
- c# - 在一个方法被覆盖的情况下使用相同的类
- php - 如何使使用 php:7.2.21-fpm 构建的 docker 容器从本地 debian 镜像安装 debian 包?
- javascript - 应用程序构建之一删除 GraphQl 'query' 字段
- c# - 如何从后面的代码将 Document 属性绑定到 FlowDocumentScrollViewer?
- r - 关于使用 R 中的 Caret 包在 LASSO 中进行预处理
- apache-beam - 使用 Apache Beam 和 ParquetIO 读取多个 parquet 文件
- sql - 使用空日期运行总计 - SQL
- java - 在 Java 中的行首或行尾点击 CSV 文件
- android - 如何更快地与 API 同步?
- c - 在链表中输入数据