Targets attribute ImageFolder

While trying to access the Targets attribute of the ImageFolder-

valdata = datasets.ImageFolder("../input/chest_xray/chest_xray/val", transform = transform)
valloader =, shuffle = True, batch_size = 64 )

for i in valdata.samples:

I get this error-

AttributeError                            Traceback (most recent call last)
<ipython-input-46-a7c7858221ef> in <module>()
     20 print(valdata.class_to_idx)
     21 print(valdata.classes)
---> 22 print(valdata.targets)
     23 for i in valdata.samples:
     24     print(i)

AttributeError: 'ImageFolder' object has no attribute 'targets'

It looks like the targets attribute was added in this PR 9 months ago. Could you try to update torchvision and try your code again?

Thanks @ptrblck

Actually, I was using Pytorch on a Kaggle Kernel.
Is there any permanent fix- so that I need not update the libraries every time I use a Kaggle Kernel?

Iā€™m not sure if Kaggle Kernels stay updated or if you would have to update certain packages in each run.
Could you try it out and let us know?

Alternatively, you might just get all targets using this line of code manually:

targets = [s[1] for s in valdata.samples]
1 Like

Thanks @ptrblck for help

Hi @ptrblck,
how do we get length of each class in this example?

If your targets are all stored in a tensor and you would like to get the count for each class, you could use torch.unique(targets, return_counts=True).