我已经建立了一个数据集,我正在对正在加载的图像进行各种检查。然后,我将此 DataSet 传递给 DataLoader。
在我的 DataSet 类中,如果图片未通过我的检查,我将样本返回为 None,并且我有一个自定义 collate_fn 函数,该函数从检索到的批次中删除所有 None 并返回剩余的有效样本。
但是,此时返回的批次可以具有不同的大小。有没有办法告诉 collate_fn 保持采购数据,直到批量大小达到一定长度?
class DataSet():
def __init__(self, example):
# initialise dataset
# load csv file and image directory
self.example = example
def __getitem__(self,idx):
# load one sample
# if image is too dark return None
# else
# return one image and its equivalent label
dataset = Dataset(csv_file='../', image_dir='../../')
dataloader = DataLoader(dataset , batch_size=4,
shuffle=True, num_workers=1, collate_fn = my_collate )
def my_collate(batch): # batch size 4 [{tensor image, tensor label},{},{},{}] could return something like G = [None, {},{},{}]
batch = list(filter (lambda x:x is not None, batch)) # this gets rid of nones in batch. For example above it would result to G = [{},{},{}]
# I want len(G) = 4
# so how to sample another dataset entry?
return torch.utils.data.dataloader.default_collate(batch)