I have coded a custom data loader class in the pytorch. But it fails when iterating through all the number of batches inside an epoch. For example, think I have 100 data examples and my batch size is 9. It will fail in the 10th iteration saying batch size is different which will give a batch size 1 instead of 10. I have put my custom data loader in below. Also I have put how I extract the data from the loader inside the for-loop.
class FlatDirectoryAudioDataset(tdata.Dataset): #customized dataloader
def __init__(self, data_dir, transform=None):
self.data_dir = data_dir
self.transform = transform
self.files = self.__setup_files()
def __len__(self):
"""
compute the length of the dataset
:return: len => length of dataset
"""
return len(self.files)
def __setup_files(self):
file_names = os.listdir(self.data_dir)
files = [] # initialize to empty list
for file_name in file_names:
possible_file = os.path.join(self.data_dir, file_name)
if os.path.isfile(possible_file) and (file_name.lower().endswith('.wav') or file_name.lower().endswith('.mp3')): #&& (possible_file.lower().endswith('.wav') or possible_file.lower().endswith('.mp3')):
files.append(possible_file)
# return the files list
return files
def __getitem__ (self,index):
sample, _ = librosa.load(self.files[index], 16000)
if self.transform:
sample=self.transform(sample)
sample = torch.from_numpy(sample)
return sample
from torch.utils.data import DataLoader
my_dataset=FlatDirectoryAudioDataset(source_directory,source_folder,source_label,transform = None,label=True)
dataloader_my = DataLoader(
my_dataset,
batch_size=batch_size,
num_workers=0,
shuffle=True)
for (i,batch) in enumerate(dataloader_my,0):
print(i)
if batch.shape[0]!=16:
print(batch.shape)
assert batch.shape[0]==16,"Something wrong with the batch size"