Search code examples
pythonmatplotlibipythongoogle-colaboratory

Using %matplotlib notebook or %matplotlib notebook does not work when run py file in colab


I have a file named utils.py. In that file I have a function named plot_results defined as below:

def plot_results(results, epochs):
    """
    The function to show results on each epoch.

    Parameters:
        results (keras.history): History of each epoch. It comes directly from keras.
        epochs (int): The number of epochs.
    """
    _, (ax1, ax2) = plt.subplots(1, 2)

    ax1.set_xlabel("Epochs")
    ax1.set_ylabel("Losses")
    ax1.plot(
        range(1, epochs+1),
        results.history['val_loss'],
        label="Validation loss",
        marker='o')
    ax1.plot(
        range(1, epochs+1),
        results.history['loss'],
        label="loss",
        marker='o')
    ax1.legend()

    ax2.set_xlabel("Epochs")
    ax2.set_ylabel("Accuracies")
    ax2.plot(
        range(1, epochs+1),
        [accuracy * 100 for accuracy in results.history['accuracy']],
        label="Accuracy",
        marker='o')
    ax2.plot(
        range(1, epochs+1),
        [accuracy * 100 for accuracy in results.history['val_accuracy']],
        label="validation accuracy",
        marker='o')
    ax2.legend()

    plt.show()

I also have a file named main.py which in that file I call plot_results. When I run main.py in local machine I get correctly the plot visualized.

But when I run it in a google colab cell as:

! python main.py --ne 1

I just get <Figure size 640x480 with 2 Axes> according to this post I tried:

%matplotlib inline
! python main.py --ne 1

And:

%matplotlib notebook
! python main.py --ne 1

And:

%matplotlib inline
%matplotlib notebook
! python main.py --ne 1

But none of them work. How can I show the plot in that function?


Solution

  • Try this

    %run main.py
    

    It will work like running line by line.