Lesson 6 - plot_function is not defined

I got that plot_function is not defined while working on the regression lesson, any idea why?

Did you import utils? I believe it’s usually this line in the notebooks

from utils import *

Yes, I did, I added both utils and fastai2.vision.all

Well, that’s where plot_function() function lives. I just want to confirm something though. You ran the utils import first and then the plot_function(…) line correct? Jupyter allows you to run cells out of order so you should see a lower number to the left “In[X]:” of the import line.

If that’s true you may want to pull the latest version of fastbook. cd to the directory of your fastbook and do git pull

Worst case here’s the source code for the function

def plot_function(f, tx=None, ty=None, title=None, min=-2, max=2, figsize=(6,4)):
    x = torch.linspace(min,max)
    fig,ax = plt.subplots(figsize=figsize)
    ax.plot(x,f(x))
    if tx is not None: ax.set_xlabel(tx)
    if ty is not None: ax.set_ylabel(ty)
    if title is not None: ax.set_title(title)```
2 Likes

One other possibility is are you doing pip install utils? Or are you doing from utils import * from within the course-v4 directory. You want to do the latter :slight_smile:

1 Like

Thank you all so much!

It worked!!!
thanks so much!

1 Like

Thank you, I was also looking for that funcion. In fastai 2.0.6 version the function is not in the utils module anymore.

Well, in fact is not in any module. I looked for it in all subdirectories of fastai but I didn’t find it.

Since it’s from the book it’s in fastbook.utils

1 Like

you can use import utils from fastbook.

or to just make plot function work you can use implementation form here-

from fastai.vision.all import plt

def plot_function(f, tx=None, ty=None, title=None, min=-2, max=2, figsize=(6,4)):
    x = torch.linspace(min,max)
    fig,ax = plt.subplots(figsize=figsize)
    ax.plot(x,f(x))
    if tx is not None: ax.set_xlabel(tx)
    if ty is not None: ax.set_ylabel(ty)
    if title is not None: ax.set_title(title)

but you do need to from fastai.vision.all import plt. I guess importing it from fastbook would be easier.

from fastbook import *

This worked for me. :slight_smile:

1 Like

installing fastbook using
pip install fastbook
worked for me

def plot_function(f, tx=None, ty=None, title=None, min=-2, max=2, figsize=(6,4)):
    x = torch.linspace(min,max, 100)
    fig,ax = plt.subplots(figsize=figsize)
    ax.plot(x,f(x))
    if tx is not None: ax.set_xlabel(tx)
    if ty is not None: ax.set_ylabel(ty)
    if title is not None: ax.set_title(title)

torch.linspace needs to assign steps parameter also. In fastbook library, 100 is assigned as default value.

2 Likes