从Keras多类模型中获取混淆矩阵

ATM*_*TMA 19 python keras

我正在用Keras构建一个多类模型.

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, callbacks=[checkpoint], validation_data=(X_test, y_test))  # starts training
Run Code Online (Sandbox Code Playgroud)

以下是我的测试数据的样子(它是文本数据).

X_test
Out[25]: 
array([[621, 139, 549, ...,   0,   0,   0],
       [621, 139, 543, ...,   0,   0,   0]])

y_test
Out[26]: 
array([[0, 0, 1],
       [0, 1, 0]])
Run Code Online (Sandbox Code Playgroud)

生成预测后......

predictions = model.predict(X_test)
predictions
Out[27]: 
array([[ 0.29071924,  0.2483743 ,  0.46090645],
       [ 0.29566404,  0.45295066,  0.25138539]], dtype=float32)
Run Code Online (Sandbox Code Playgroud)

我做了以下以获得混淆矩阵.

y_pred = (predictions > 0.5)

confusion_matrix(y_test, y_pred)
Traceback (most recent call last):

  File "<ipython-input-38-430e012b2078>", line 1, in <module>
    confusion_matrix(y_test, y_pred)

  File "/Users/abrahammathew/anaconda3/lib/python3.6/site-packages/sklearn/metrics/classification.py", line 252, in confusion_matrix
    raise ValueError("%s is not supported" % y_type)

ValueError: multilabel-indicator is not supported
Run Code Online (Sandbox Code Playgroud)

但是,我收到了上述错误.

在Keras中进行多类神经网络时如何获得混淆矩阵?

Nea*_*bfi 28

您的输入confusion_matrix必须是一个int数组而不是一个热编码.

matrix = metrics.confusion_matrix(y_test.argmax(axis=1), y_pred.argmax(axis=1))
Run Code Online (Sandbox Code Playgroud)

  • 如果它太微妙,这个答案澄清了问题是关于“sklearn.metrics.confusion_matrix()”,而不是“tensorflow.math.confusion_matrix()”,考虑到标签“keras”,这可能是预期的 (25认同)
  • 如何将它用于图像数据集? (2认同)