How can I print the shape of a ImageFolder?

I am using an ImageFolder to access my Google Drive folder in Colab and then using Dataloader to load the Images from four classes. Now I want to know the shape of the test-class.

# choose the training and test datasets
train_data = datasets.ImageFolder(data+"/train", transform=transform_train)
test_data = datasets.ImageFolder(data+"/val", transform = transform_test)
#n_classes = test_data.shape[1]

dataloader_train = torch.utils.data.DataLoader(train_data, batch_size=32, shuffle=True, num_workers=2)
dataloader_test = torch.utils.data.DataLoader(test_data, batch_size=32, num_workers=2)
n_classes = dataloader_test.shape[1]

Each time I try to do this, resulting error like this -
AttributeError: 'DataLoader' object has no attribute 'shape' or
AttributeError: 'ImageFolder' object has no attribute 'shape'
Any idea how can I print the shape of the test class?

What do you mean by shape?
If you would like to get the length of the dataset, you could use print(len(test_data)).
However, if you would like to get the shape of a sample, you could use
print(test_data[0][0].shape).
Note that this will only print the shape of the first data sample.
If you don’t resize all images to the same size, each sample could have a different shape.

I want to get the class number by printing the shape of it. There are four classes, so I want to get the number of this by doing this - n_classes = test_data.shape[1]?
I have print this - print(len(test_data)) and giving me 32 and printing this - print(test_data[0][0].shape) gicing me this error -
OSError: cannot identify image file <_io.BufferedReader name='/content/drive/My Drive/AMD_new/val/CNV/CNV-6294785-1.jpeg'>
Can you please tell me is my concept right that I can get the class number by printing shape of the first colomn of the test_data, which has four folder in drive?

ImageFolder will create targets using class indices. They won’t be in a one-hot encoded format, so the shape of the target won’t give you the number of classes.
However, this code should work:

n_classes = len(dataset.classes)

Got it thanks a lot, but how did you do that? I mean where should I know how to do something with ImageFolder? Thanks though.

Depending on your IDE you could just type dataset. and TAB to get all member attributes and functions or alternatively you could use print(dir(dataset)).
Also the source code is very helpful. :wink:

2 Likes