如何计算或绘制CNN中每个类别的误差?

时间:2019-07-06 08:41:37

标签: python-3.x neural-network classification loss

我在项目中使用了此代码,但我想计算或绘制每个类的错误。我有6个类。我该怎么办?

def plot_history(net_history):
    history = network_history.history
    losses = history['loss']
    accuracies = history['acc']
    plt.xlabel('Epochs')
    plt.ylabel('loss')
    plt.plot(losses)

    plt.figure()
    plt.xlabel('Epochs')
    plt.ylabel('accuracy')
    plt.plot(accuracies)

创建我的模型

myinput = layers.Input(shape=(100,200))
conv1 = layers.Conv1D(16, 3, activation='relu', padding='same', strides=2)(myinput)
conv2 = layers.Conv1D(32, 3, activation='relu', padding='same', strides=2)(conv1)
flat = layers.Flatten()(conv2)
out_layer = layers.Dense(6, activation='softmax')(flat)

mymodel = Model(myinput, out_layer)
mymodel.summary()
mymodel.compile(optimizer=keras.optimizers.Adam(), 
loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])

训练我的模型

network_history = mymodel.fit(X_train, Y_train, batch_size=128,epochs=5, validation_split=0.2)
plot_history(network_history)

评估

test_loss, test_acc = mymodel.evaluate(X_test, Y_test)

test_labels_p = mymodel.predict(X_test)

2 个答案:

答案 0 :(得分:0)

评估分类器的一种简单方法是scikit-learn中的classification_report

from sklearn.metrics import classification_report

....

# Actual predictions here, not just probabilities
pred = numpy.round(mymodel.predict(X_test))
print(classification_report(Y_test, pred))

其中Y_test是一键向量的列表。

这将向您显示每个班级的精度,召回率和f1度量。缺点是它仅考虑预测是正确还是错误,并且没有考虑模型的确定性。

答案 1 :(得分:0)

您必须像二进制分类问题一样训练它,然后您可以使用此代码为不同的类制作学习曲线:

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