Importing images

Could someone please explain what exactly happens in this line of code?
I’m mainly confused by “index % len(self.files_A)”.

item_A = self.transform([index % len(self.files_A)]))


Hi @viedschi!

% is the modulo operator, it returns the remainder of an integer division, e.g. 5 % 2 = 1.

I suppose index can be larger than the length of self.files_A. When that is the case, you can’t do self.files_A[index] as that would result in

IndexError: list index out of range

By taking the remainder of the division of index by len(self.files_A), you are guaranteed to have a valid index for self.files_A, since this value will always be smaller than the length of the list.

Hope this helps, cheers

And the reason we do that for self.files_A but not for self.files_B is that we have defined A to be the smallest dataset:

class ImageDataset(Dataset):
    def __init__(self, root, transform=None, mode='train'):
        if len(self.files_A) > len(self.files_B):
            self.files_A, self.files_B = self.files_B, self.files_A

Here Index could be far larger than the len(self.files_A), we will open the images based on the remainer. This format will be safe for both index length