防止Pythorch数据集迭代超过数据长度

2024-06-06 20:55:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的自定义Pythorch数据集包含以下内容:

class ImageDataset(Dataset):
    def __init__(self, input_dir, input_num, input_format, transform=None):
        self.input_num = input_num
        # etc
    def __len__ (self):
        return self.input_num
    def __getitem__(self,idx):
        targetnum = idx % self.input_num
        # etc

但是,当我迭代这个数据集时,迭代循环回到数据集的开始,而不是在数据集的末尾终止。这实际上成为迭代器中的一个无限循环,epoch print语句永远不会出现在后续的epoch中。在

^{2}$

打印输出(。。。对于介于两者之间的值):

EPOCH 1
0 1 2 3 4 5 6 7 ... 298 299 300 301 302 303 304 305 ... 597 598 599 600 601 602 603 604 ...

为什么对数据集的基本迭代会持续超过定义的数据集__len__,在使用此方法时,如何确保在数据集上的迭代在达到数据集长度后终止(或者手动迭代数据集长度的范围是唯一的解决方案)?在

谢谢。在


Tags: 数据selfinputleninitdefdiretc
1条回答
网友
1楼 · 发布于 2024-06-06 20:55:21

Dataset类没有实现StopIteration信号。在

The for loop listens for StopIteration. The purpose of the for statement is to loop over the sequence provided by an iterator and the exception is used to signal that the iterator is now done...

更多:Why does next raise a 'StopIteration', but 'for' do a normal return?| The Iterator Protocol

相关问题 更多 >