【发布时间】:2020-08-06 05:28:43
【问题描述】:
我在 Jupyter 笔记本中运行了一个神经网络,我想绘制结果(损失与纪元数)。我可以毫无问题地运行模型,但即使是简单的 matplotlib 绘图也会杀死内核。
这是创建我要使用的模型和数据的代码:
from keras import models
from keras import layers
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
from keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data( num_words=10000)
# Change review into array
def vectorize_sequences(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension)) # create all-zero matrix
for i, sequence in enumerate(sequences):
results[i, sequence] = 1. # If review has word, change that index to 1
return results
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')
# Create model
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,))) # two int. layers w/16 hidden units each
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid')) # outputs the scalar prediction
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
# Create mini-test data
x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]
# fit model
history = model.fit(partial_x_train, partial_y_train, epochs=20, batch_size=512, validation_data=(x_val, y_val))
# Get values for plot
history_dict = history.history
history_dict.keys()
loss_values = history_dict['loss']
val_loss_values = history_dict['val_loss']
epoch_num = [i for i in range(1,21)]
这按预期工作。但是,当我尝试使用下面的代码绘制数据时,我收到一条消息:“内核似乎已经死机。它将自动重新启动。”
plt.plot(epoch_num, loss_values, 'bo', label='Training loss')
plt.plot(epoch_num, val_loss_values, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
我可以重新启动内核并制作 matplotlib 绘图,但是当我在运行模型 matplotlib 后尝试制作绘图时会出现错误。我试过更新 keras、tensorflow、matplotlib 和 numpy 都没有效果。谁能提供有关为什么会发生这种情况的见解并提供解决方案?
【问题讨论】:
-
你最初的损失值是否也有 nan ?
-
不,loss_values 或 val_loss_values 中没有 NaN
-
训练模型后你检查你的内存了吗?还剩多少?我猜你没有足够的内存来运行 matplotlib。使用
htop检查内存统计信息。 -
该型号使用 3.79GB 内存。我的电脑上有 64GB 的内存。该模型运行没有问题。之后我就不能使用matplotlib了。
标签: python tensorflow matplotlib keras jupyter-notebook