How to import PILImage?

When I run the 01_intro code from my local Visual Studio Code:

img = PILImage.create(image_cat())
img.to_thumb(192)

I get the following error message:

NameError                                 Traceback (most recent call last)
<ipython-input-4-282e3835da02> in <module>
      1 from fastai.data.external import *
----> 2 img = PILImage.create(image_cat())
      3 img.to_thumb(192)

NameError: name 'PILImage' is not defined

So, I go to Core vision and am led to think that I need to add "from fastai.data.external import " to my 01_intro notebook code as follows, to actually import PILImage:

from fastai.data.external import *
img = PILImage.create(image_cat())
img.to_thumb(192)

but when I run that I get the same error.

Can someone tell me how to read the API so that I can deal with such errors?

If you import from fastai.vision.all import * then you should be fine. What is the version of your fastai?

OK, I’m really trying to learn how to use these error messages and the API to fix things on my own, but it’s tough. Why does Core vision present from fastai.data.external import * if that doesn’t import what is listed on that page? If I’m going to write my own code later I need to understand this.

fastai version: 2.1.5

I tried your suggestion:

#from fastai.data.external import * #this is here because of Core vision seeming to tell me to use it
print(fastai.__version__)
from fastai.vision.all import * #trying this instead as per ilovescience's reply
img = PILImage.create(image_cat())
img.to_thumb(192)

and now get the following error message:

NameError                                 Traceback (most recent call last)
<ipython-input-12-b27ae278b750> in <module>
      1 #from fastai.data.external import *
----> 2 from fastai.vision.all import *
      3 img = PILImage.create(image_cat())
      4 img.to_thumb(192)

C:\Users\jbiss\AppData\Local\Programs\Python\Python36\lib\site-packages\fastai\vision\all.py in <module>
----> 1 from . import models
      2 from ..basics import *
      3 from ..callback.all import *
      4 from .augment import *
      5 from .core import *

C:\Users\jbiss\AppData\Local\Programs\Python\Python36\lib\site-packages\fastai\vision\models\__init__.py in <module>
      1 from . import xresnet
----> 2 from . import unet
      3 from .tvm import *

C:\Users\jbiss\AppData\Local\Programs\Python\Python36\lib\site-packages\fastai\vision\models\unet.py in <module>
      5 # Cell
      6 from ...torch_basics import *
----> 7 from ...callback.hook import *
      8 
      9 # Cell

C:\Users\jbiss\AppData\Local\Programs\Python\Python36\lib\site-packages\fastai\callback\hook.py in <module>
      5 
      6 # Cell
----> 7 from ..basics import *
      8 
      9 # Cell

C:\Users\jbiss\AppData\Local\Programs\Python\Python36\lib\site-packages\fastai\basics.py in <module>
      1 from .data.all import *
      2 from .optimizer import *
----> 3 from .callback.core import *
      4 from .learner import *
      5 from .metrics import *

C:\Users\jbiss\AppData\Local\Programs\Python\Python36\lib\site-packages\fastai\callback\core.py in <module>
     29 # Cell
     30 @funcs_kwargs(as_method=True)
---> 31 class Callback(Stateful,GetAttr):
     32     "Basic class handling tweaks of the training loop by changing a `Learner` in various events"
     33     _default,learn,run,run_train,run_valid = 'learn',None,True,True,True

NameError: name 'Stateful' is not defined

So, no go.

Try upgrading your fastcore version

2 Likes

Happy Sunday! I couldn’t find instructions for upgrading, so I ran an install of fastcore and the process shows that I have version 1.3.13 and that’s the latest version that python shows (at https://pypi.org/project/fastcore/).

I just started looking through C:\Users\jbiss\AppData\Local\Programs\Python\Python36\Lib\site-packages\fastai and found /callback/core and think that the argument Stateful would come from either:

from ..data.all import *
from ..optimizer import *

I searched for optimizer in the /Python/Python36/Lib tree and there are a number of results and searching for data.all returns no results.

Fastcore 1.3.5 added the Stateful class and it’s still there, so that shouldn’t be an issue. When you are saying that you checked and saw you had fastcore 1.3.5, how did you check that? The best way would be to go to python and do:

import fastcore
print(fastcore.__version__)

I was told that I have Fastcore 1.3.13 when I ran pip install fastcore because I didn’t know how to command an upgrade. The process said Requirement already satisfied: fastcore in c:/users…/site-packages (1.3.13). I just ran your code and it displayed the same thing, version 1.3.13.

class Callback doesn’t address Stateful except to mention it and the class Callback in C:\Users\jbiss\AppData\Local\Programs\Python\Python36\Lib\site-packages\fastai\callback\core.py indicates that it is just an argument passed to it.

Did you run in the same script you imported fastai.vision.all?

Also, here is the documentation for Stateful. You should be able to run this code without any error if Stateful is appropriately defined:

class _T(Stateful):
    def __init__(self):
        super().__init__()
        self.a=1
        self._state['test']=2

t = _T()
t2 = pickle.loads(pickle.dumps(t))
test_eq(t.a,1)
test_eq(t._state['test'],2)
test_eq(t2.a,1)
test_eq(t2._state,{})

Finally, Callback is not using Stateful as an argument. It is subclassing the Stateful class and inheriting its behavior.

OK. I don’t the time to perform the code in Running Your First Notebook of 01_intro.ipynb that would get me to the point that the original error occurs, but I went to the beginning and added that code (from class Stateful as follows:

#hide
from fastbook import *
#the following are due to problems with "Stateful" not being defined later
import fastcore
print(fastcore.__version__)
from fastai.vision.all import *
class _T(Stateful):
    def __init__(self):
        super().__init__()
        self.a=1
        self._state['test']=2

t = _T()
t2 = pickle.loads(pickle.dumps(t))
test_eq(t.a,1)
test_eq(t._state['test'],2)
test_eq(t2.a,1)
test_eq(t2._state,{})
print('Done!')

It performed without error. At this moment I don’t understand why I got no error with that but did previously from the point ----> 2 from fastai.vision.all import * shown above.

OK, I performed 01_intro.ipynb but commented out lines as follows:

print(fastai.__version__)
#from fastai.vision.all import *
#import fastcore
img = PILImage.create(image_cat())
img.to_thumb(192)

and got a fastai not defined error because I forgot to comment that print statement out. So, I added import fastai to the code:

import fastai
print(fastai.__version__)
#from fastai.vision.all import *
#import fastcore
img = PILImage.create(image_cat())
img.to_thumb(192)

and voila! the kitten picture appeared along with the fastai version! Therefore, it seems that there are differences in code performance between using the notebook in paperspace and Windows 10 that require mutually exclusive “imports” in one and not the other. In this case, the default notebook code runs fine with no errors in paperspace but requires me to add imports in the notebook code in Windows 10.

I suppose when I develop in Windows 10 I need to import fastai at the very beginning of the notebook with fastbook:

#hide
from fastbook import *
import fastai

This should fix at least some of these “not defined” errors across the board. Maybe we need to document some of these OS differences? There are other problems with Windows 10, such as the notebook complaining about no response and having to be reset, which loses the previous environment.

1 Like

You should also be mindful to always set num_workers=0 in your dataloaders (just pass this as a param to anything making DataLoaders), as windows doesn’t allow multiprocessing for us. You’ll run into another headache later if you do not.

As I suggested on a Stack Overflow post.

Not sure if this helps…

You may want to import PIL image as:

from PIL import Image as PILImage

Adapted from Source | line 12.

No this is incorrect, PILImage is a fastai class, and not from the PIL library. Things will likely break if you import the Pillow Image class as PILImage.

2 Likes

Fair, it worked for me but will keep an eye out for weird behaviour

1 Like

from fastai.vision.all import PILImage

this will work, I think u just have to manually import it if u didn’t import all

I am using fastai version 2.7.18.

NameError Traceback (most recent call last)
in
1 from fastai.data.external import *
----> 2 img = PILImage.create(image_cat())
3 img.to_thumb(192)

NameError: name ‘PILImage’ is not defined

i am facing the same error. How do I get past it?