簡體   English   中英

Jupyter Notebook和MatPlotLib不繪制Keras結果

[英]Jupyter Notebook and MatPlotLib Not Plotting Keras Results

我正在使用Anaconda 1.9.7安裝的Jupyter Notebook來運行使用Tensorflow,Keras,Python 3.x和Matplotlib的機器學習模型。 當我從Mac上的終端運行代碼時,一切運行正常,圖形繪制到外部窗口。 當我在Jupyter Notebook中運行相同的代碼時,內核會死亡並在第一次使用Matplotlib的代碼重新啟動。

最初,我沒有使用“%matplotlib inline”,所以我將其添加到頂部,但是該圖仍然沒有顯示。 我創建了一個簡單的用例(不是此處提供的機器學習代碼),並將該圖內聯繪制到Jupyter Notebook。 當我從Mac上的終端運行當前代碼時,它可以正常工作,並且圖形顯示到外部窗口。

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()

我希望最后一行在Jupyter Notebook中內聯繪制圖形。 相反,內核在“ plt.title('Training andvalidation loss')”行死亡,並且當我獨立運行該行時,出現錯誤“ NameError:未定義名稱'plt'”。

我嘗試了一些修改后的代碼:

  • 注釋了以下幾行:
    • np_load_old = np.load
    • np.load = lambda *a, **l: np_load_old ...
    • np.load = np_load_old

而且有效。 我得到以下情節:

在此處輸入圖片說明

我的版本是:

  • 張量流1.13.1
  • matplotlib 3.1.1
  • jupyter 1.0.0
  • python 3.6.6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM