PyTorch:为什么我的数据集类给出索引超出范围错误?

Joh*_*tud 5 python h5py pytorch

我试图找出为什么我的数据集给出超出范围的索引错误。

考虑这个火炬数据集:

# prepare torch data set
class MSRH5Processor(torch.utils.data.Dataset):
    def __init__(self, type, shard=False, **args):
        # init configurable string
        self.type = type
        # init shard for sampling large ds if specified
        self.shard = shard
        # set seed if given
        self.seed = args
        # set loc
        self.file_path = 'C:\\data\\h5py_embeds\\'
        # set file paths
        self.val_embed_path = self.file_path + 'msr_dev_bert_embeds.h5'

        # if true, initialize the dev data
        if self.type == 'dev':
            # embeds are shaped: [layers, tokens, features]
            self.embeddings = h5py.File(self.val_embed_path, 'r')["embeds"]

    def __len__(self):
        return len(self.embeddings)

    def __getitem__(self, idx):
        if torch.is_tensor(idx):
            idx = idx.tolist()

        if self.type == 'dev':
            sample = {'embeddings': self.embeddings[idx]}
            return sample

# load dataset
processor = MSRH5Processor(type='dev', shard=False)
# check length
len(processor)  # 22425

# iterate over the samples
count = 0
for step, batch in enumerate(processor):
    count += 1
# error: Index (22425) out of range (0-22424)

with h5py.File('C:\\w266\\h5py_embeds\\msr_dev_bert_embeds.h5', 'r') as f:
    print(f['embeds'].attrs['last_index'])  # 22425
    print(f['embeds'].shape)  # (22425, 128, 768)
    print(len(f['embeds']))  # 22425
Run Code Online (Sandbox Code Playgroud)

如果我手动将数据集长度更改为10022424,我仍然会得到相同的错误。是什么告诉 PyTorch 寻找索引 22425?

如果我要制作一个包含 1000 个观察值(其中len = 1000)的 CSV 数据集,它将停止__getitem__()在 999 而不是 1000 处将索引输入到方法中。

编辑:

这似乎只是 Dataset 类和 H5py 文件的问题。如果我使用火炬数据加载器,它将运行到我的数据集的自然长度。尽管如此,我很想知道 Torch 正在做什么来获取我的 H5 文件的这个数字,这导致它的行为与 CSV 不同。

Pro*_*oko 3

要用作Dataset可迭代对象,您必须实现任一__iter__方法或__getitem__使用序列语义。当方法针对某些索引idx__getitem__引发时迭代停止IndexError

您的数据集的问题在于:

self.embeddings = h5py.File(self.val_embed_path, 'r')["embeds"]
Run Code Online (Sandbox Code Playgroud)

h5py._hl.dataset.Dataset实际上是索引外请求引发的类型ValueError

您必须在类构造函数中加载整个嵌入,以便访问索引外的 numpy 数组将引发IndexError 或重新IndexError抛出ValueErrorin__getitem__