'ModuleNotFoundError: No module named 'fastai.vision'

I am trying to use ImageDataBunch from fastai, and it worked fine, but recently when I ran my code, it showed this error ModuleNotFoundError: No module named 'fastai.vision'

Then, I upgraded my fastai version pip install fastai --upgrade. This error got cleared but landed in NameError: name 'ImageDataBunch' is not defined

Here's my code:

import warnings
import numpy as np
from fastai.vision import *
warnings.filterwarnings("ignore", category=UserWarning, module="torch.nn.functional")
data = ImageDataBunch.from_folder(path, train='.', valid_pct=0.2, 
                                  ds_tfms=get_transforms(), size=224, num_workers=4, no_check=True).normalize(imagenet_stats)

How can I fix this?

Solution 1:[1]

I actually ran into this same issue when I started using Colab, but haven't been able to reproduce it. Here was the thread describing what I and another developer did to troubleshoot: https://forums.fast.ai/t/no-module-named-fastai-data-in-google-colab/78164/4

I would recommend trying to factory reset your runtime ( "Runtime" -> "Factory Reset Runtime")

Then you can check which version of fastai you have (you have to restart the runtime to use the new version if you've already imported it)

import fastai

I'm able to run fastai.vision import * on fastai version 1.0.61 and 2.0.13

Solution 2:[2]

In Google Colab:

Upgrade fastai on colab:

! [ -e /content ] && pip install -Uqq fastai 

Import necessary libraries:

from fastai.vision.all import *
from fastai.text.all import *
from fastai.collab import *
from fastai.tabular.all import * 

Get the images and annotations:

path = untar_data(URLs.PETS)
path_anno = path/'annotations'
path_img = path/'images'
print( path_img.ls() )             # print all images
fnames = get_image_files(path_img) # -->> 7390 images
print(fnames[:5])                  # print first 5 images 

Solution 3:[3]

The solution that worked for me is to copy to (connect) my google drive & then run the cells. Source

Click on "Copy to Drive"

Solution 4:[4]

You might have installed the older version of fastai. You need to upgrade to fastaiv2. You can upgrade fastai by using pip as shown below.

!pip install fastai --upgrade

Also check your fastai version using

import fastai


This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman
Solution 2 Farid Alijani
Solution 3 anjandash
Solution 4 Hemanth Kollipara