混淆矩阵错误“分类指标无法处理多标签指标和多类目标的混合”

我得到一个


Classification metrics can't handle a mix of multilabel-indicator and multiclass targets

当我尝试使用混淆矩阵时出错。


我正在做我的第一个深度学习项目。我是新手。我正在使用由 keras 提供的 mnist 数据集。我已经成功地训练和测试了我的模型。


但是,当我尝试使用 scikit learn 混淆矩阵时,我收到了上述错误。我已经搜索了一个答案,虽然有关于这个错误的答案,但没有一个对我有用。从我在网上找到的内容来看,它可能与损失函数有关(我categorical_crossentropy在我的代码中使用了)。我尝试将其更改为,sparse_categorical_crossentropy但这只是给了我


Error when checking target: expected dense_2 to have shape (1,) but got array with shape (10,)

当我fit()在模型上运行该函数时。


这是代码。(为简洁起见,我省略了进口)


model = Sequential()

model.add(Dense(512, activation='relu', input_shape=(28 * 28,)))

model.add(Dense(10, activation='softmax')) 


model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['accuracy'])


(train_images, train_labels), (test_images, test_labels) = mnist.load_data()


train_images = train_images.reshape((60000, 28 * 28))

train_images = train_images.astype('float32') / 255


test_images = test_images.reshape((10000, 28 * 28))

test_images = test_images.astype('float32') / 255


train_labels = to_categorical(train_labels)

test_labels = to_categorical(test_labels)


model.fit(train_images, train_labels, epochs=10, batch_size=128)


rounded_predictions = model.predict_classes(test_images, batch_size=128, verbose=0)


cm = confusion_matrix(test_labels, rounded_predictions)

我怎样才能解决这个问题?


跃然一笑
浏览 468回答 2
2回答

千万里不及你

混淆矩阵需要将标签和预测作为个位数,而不是作为单热编码向量;尽管您已经使用model.predict_classes(),即rounded_predictions = model.predict_classes(test_images, batch_size=128, verbose=0)rounded_predictions[1]# 2你test_labels仍然是one-hot编码:test_labels[1]# array([0., 0., 1., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)因此,您也应该将它们转换为个位数,如下所示:import numpy as nprounded_labels=np.argmax(test_labels, axis=1)rounded_labels[1]# 2之后,混淆矩阵应该会出现:from sklearn.metrics import confusion_matrixcm = confusion_matrix(rounded_labels, rounded_predictions)cm# result:array([[ 971,    0,    0,    2,    1,    0,    2,    1,    3,    0],       [   0, 1121,    2,    1,    0,    1,    3,    0,    7,    0],       [   5,    4,  990,    7,    5,    3,    2,    7,    9,    0],       [   0,    0,    0,  992,    0,    2,    0,    7,    7,    2],       [   2,    0,    2,    0,  956,    0,    3,    3,    2,   14],       [   3,    0,    0,   10,    1,  872,    3,    0,    1,    2],       [   5,    3,    1,    1,    9,   10,  926,    0,    3,    0],       [   0,    7,   10,    1,    0,    2,    0,  997,    1,   10],       [   5,    0,    3,    7,    5,    7,    3,    4,  937,    3],       [   5,    5,    0,    9,   10,    3,    0,    8,    3,  966]])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python