I'm using Jupyter Notebook installed by Anaconda 1.9.7 to run a machine learning model using Tensorflow, Keras, Python 3.x, and Matplotlib. When I run the code from the Terminal on my Mac everything runs fine and the graph is plotted to an external window. When I run the same code in Jupyter Notebook, the kernel dies and restarts the first time the code uses Matplotlib.
Initially, I was not using "%matplotlib inline" so I added this to the top, but the graph still does not show. I created a simple use case (not the machine learning code provided here) and the graph plotted inline to Jupyter Notebook. The current code works without a problem when I run it from the Terminal on my Mac, and the graph displays to external window.
get_ipython().run_line_magic('matplotlib', 'inline')
import tensorflow as tf
from keras.datasets import reuters
import numpy as np
np_load_old = np.load
np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)
np.load = np_load_old
word_index = reuters.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
decoded_newswire = ' '.join([reverse_word_index.get(i - 3, '?') for i in train_data[10]])
decoded_newswire
def vectorize_sequences(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1
return results
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
from keras.utils.np_utils import to_categorical
one_hot_train_labels = to_categorical(train_labels)
one_hot_test_labels = to_categorical(test_labels)
from keras import models
from keras import layers
model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(46, activation='softmax'))
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
x_val = x_train[:1000]
partial_x_train = x_train[1000:]
y_val = one_hot_train_labels[:1000]
partial_y_train = one_hot_train_labels[1000:]
history = model.fit(partial_x_train, partial_y_train, epochs=3, batch_size=512, validation_data=(x_val, y_val))
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(loss) + 1)
import matplotlib.pyplot as plt
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.show()
I expect the last line to plot a graph inline in Jupyter Notebook. Instead, the Kernel dies at the line "plt.title('Training and validation loss')" and when I run the line independently it give the error "NameError: name 'plt' is not defined."