Keras - 绘制训练、验证和测试集的准确率图表

85

我想绘制这个简单神经网络的输出:

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(x_test, y_test, nb_epoch=10, validation_split=0.2, shuffle=True)

model.test_on_batch(x_test, y_test)
model.metrics_names

我已经绘制了训练和验证的准确度损失

print(history.history.keys())
#  "Accuracy"
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# "Loss"
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()

现在我想添加和绘制测试集的准确性,使用model.test_on_batch(x_test, y_test),但是从model.metrics_names中我获得了相同的值'acc'用于绘制训练数据准确性plt.plot(history.history['acc'])。我该如何绘制测试集准确性?


可能是原始代码的来源:在Keras中显示深度学习模型训练历史 - Trenton McKinney
6个回答

143
import keras
from matplotlib import pyplot as plt
history = model1.fit(train_x, train_y,validation_split = 0.1, epochs=50, batch_size=4)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()

模型准确率

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()

模型损失


34
仅做小的补充:在更新后的Keras和Tensorflow 2.0中,关键字"acc"和"val_acc"已相应更改为"accuracy"和"val_accuracy"。因此,plt.plot(history.history['acc']) plt.plot(history.history['val_acc'])需要更改为plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy'])(注:我正在使用Keras版本2.2.4) - EMT
1
我意识到了这一点,回到这里评论同样的事情,然后看到你已经做到了。这太棒了! - Vasanth Nag K V
1
@EMT 不取决于使用“accuracy”或“acc”的Tensorflow版本,而是取决于您自己的命名。tf.version.VERSION给出了'2.4.1'。我使用“accuracy”作为键仍然得到了KeyError: 'accuracy',但是“acc”可以工作。如果您使用metrics=["acc"],则需要调用history.history['acc']。如果您在loss="categorical_crossentropy"的情况下使用metrics=["categorical_accuracy"],则需要调用history.history['categorical_accuracy'],以此类推。请参见history.history.keys()以获取所有选项。 - questionto42

42

尝试

pd.DataFrame(history.history).plot(figsize=(8,5))
plt.show()

这将为历史记录中所有数据集的可用指标建立一个图表。例如:

enter image description here


24

因为您正在测试集上训练,而不是在训练集上训练,所以它是相同的。不要这样做,只需在训练集上进行训练:

history = model.fit(x_test, y_test, nb_epoch=10, validation_split=0.2, shuffle=True)

转换为:

history = model.fit(x_train, y_train, nb_epoch=10, validation_split=0.2, shuffle=True)

对不起,我一直使用训练集来训练神经网络,这是我的疏忽。我是机器学习的新手,对 model.fit( ... ) 的结果有些困惑,我得到了 loss_、_acc_、_val__loss 和 _val__acc_,我认为这些值代表训练和验证的损失和准确性,但我在哪里可以找到关于测试的损失值呢? - Simone
@Simone 你可以在测试集上使用 model.evaluate 来获取测试集上的损失和指标。只需确保使用正确的变量即可。 - Dr. Snoopy
我已经使用了 _model.evaluate_,并获得了 accuracy 和 _loss_,但由于无法区分训练集上获得的 accuracy 和测试集上获得的 _accuracy_,所以我无法将它们绘制成图表。 - Simone
@Simone 你的意思是不能区分吗? - Dr. Snoopy
@Simone,我们没有足够的信息告诉您哪里出了问题。 - Dr. Snoopy
显示剩余2条评论

10

按照下面所示的方式在测试数据上验证模型,然后绘制准确度和损失图表。

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(X_train, y_train, nb_epoch=10, validation_data=(X_test, y_test), shuffle=True)

7
你也可以用这种方式来实现...
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error',metrics=['accuracy'])
earlyStopCallBack = EarlyStopping(monitor='loss', patience=3)
history=regressor.fit(X_train, y_train, validation_data=(X_test, y_test), epochs = EPOCHS, batch_size = BATCHSIZE, callbacks=[earlyStopCallBack])

对于绘图 - 我喜欢使用plotly...所以

import plotly.graph_objects as go
from plotly.subplots import make_subplots

# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])

# Add traces
fig.add_trace(
    go.Scatter( y=history.history['val_loss'], name="val_loss"),
    secondary_y=False,
)

fig.add_trace(
    go.Scatter( y=history.history['loss'], name="loss"),
    secondary_y=False,
)

fig.add_trace(
    go.Scatter( y=history.history['val_accuracy'], name="val accuracy"),
    secondary_y=True,
)

fig.add_trace(
    go.Scatter( y=history.history['accuracy'], name="val accuracy"),
    secondary_y=True,
)

# Add figure title
fig.update_layout(
    title_text="Loss/Accuracy of LSTM Model"
)

# Set x-axis title
fig.update_xaxes(title_text="Epoch")

# Set y-axes titles
fig.update_yaxes(title_text="<b>primary</b> Loss", secondary_y=False)
fig.update_yaxes(title_text="<b>secondary</b> Accuracy", secondary_y=True)

fig.show()

enter image description here

以上两种方法均无问题。请注意,Plotly图表具有两个刻度,一个用于损失率,另一个用于准确率。


1

在绘制图表时使用accuracyval_accuracy


中绘制准确率

plt.plot(model.history.history["accuracy"], label="training accuracy")
plt.plot(model.history.history["val_accuracy"], label="validation accuracy")
plt.legend()
plt.show()

accuracy graph

中绘制 loss

plt.plot(model.history.history["loss"], label="training loss")
plt.plot(model.history.history["val_loss"], label="validation loss")
plt.legend()
plt.show()

loss graph


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接