TypeError: 'module' object is not subscriptable (Pytorch)

Viewed 1607

I'm currently self studying and implementing PyTorch. While doing transfer learning with this tutorial: https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html

I encountered an error in this particular code block:

image_datasets = {x: datasets.ImageFolder(os.path.join(main_dataset, x),
                                          transforms[x])
                 for x in ['Train','Test']}

The error code is as below:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-41-c83fc3ba4a1c> in <module>()
      1 image_datasets = {x: datasets.ImageFolder(os.path.join(main_dataset, x),
      2                                           transforms[x])
----> 3                 for x in ['Train','Test']}

<ipython-input-41-c83fc3ba4a1c> in <dictcomp>(.0)
      1 image_datasets = {x: datasets.ImageFolder(os.path.join(main_dataset, x),
      2                                           transforms[x])
----> 3                 for x in ['Train','Test']}

TypeError: 'module' object is not subscriptable

Which I am certain I have not used any module wrongly or any typos in this particular code block.

While searching the error code, I did not find anything related to this as well.

Please help, thanks.

1 Answers

Quoting @Mustafa Aydin

You need to write data_transforms[x] instead of transforms[x] where the error points to. As it stands, you are trying to index torchvision.transforms (which you imported as e.g. from torchvision import transforms), hence the error.

I declared a variable named transforms and it confuses the compiler as it clashes with torchvision.transforms.

Hence the issue presented here.

Related