【问题标题】:confusion_matrix() | ValueError: Classification metrics can't handle a mix of multiclass and multiclass-multioutput targets混淆矩阵() | ValueError:分类指标无法处理多类和多类多输出目标的混合
【发布时间】:2021-06-25 07:44:59
【问题描述】:

之前肯定有人问过,但我没有成功分析其他帖子针对我自己的这个问题实例的解决方案。

我有很多分类模型要使用confusion_matrix()进行比较

matrix = confusion_matrix(y_test, y_pred) # ERROR
>>> y_pred
[[2 2 2 ... 2 2 2]
 [2 2 2 ... 2 2 2]
 [2 2 2 ... 2 2 2]
 ...
 [3 3 2 ... 3 2 3]
 [2 2 2 ... 2 2 2]
 [3 3 3 ... 3 3 3]]
>>> y_pred.shape
(500, 256)
>>> y_test
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3]
>>> y_test.shape
(500, )

错误:

ValueError: Classification metrics can't handle a mix of multiclass and multiclass-multioutput targets

.flatten()y_pred 执行时 - 即一维数组 (500 * 256 = 128000):

ValueError: Found input variables with inconsistent numbers of samples: [500, 128000]

【问题讨论】:

  • y_pred 应该是一维数组以进行比较
  • 你的 y_pred 是如何进入二维数组的?你在 y 做了哪些预处理?
  • 所以我将 'y_pred = model.predict(X_test_seq)' 转换为与 'X_test_seq' 相同的形状
  • y_pred扁平化后的形状是什么?
  • 你能告诉我预测的[2,2,2,2....2] 是什么意思吗?你的 y 是多少?

标签: python neural-network classification confusion-matrix multilabel-classification


【解决方案1】:

混淆矩阵的工作基于每个预测值与实际值之间的比较。不可能将1[2,2,2....2,2,2] 进行比较

在您的情况下,您的 y_pred 是 2d,但您的 y_test 是 1d,这就是实际错误出现的地方。我相信你必须在你的预测列表中选择最常见的数字。喜欢2 来自[2,2,2....2,2]

所以这里是解决方案:

from scipy import stats 
import numpy as np

#taking the most frequent element from the predicted list
y_pred_list = [int(stats.mode(arr)[0]) for arr in y_pred.tolist()] #convert to list

y_pred_array = np.array(y_pred_list)  #convert to 1D with same shape of y_test

print(y_pred_array.shape)

print(y_pred_array)

matrix = confusion_matrix(y_test, y_pred_array)

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 2021-05-14
    • 2018-08-26
    • 2019-10-23
    • 2021-12-20
    • 2019-09-07
    • 2021-04-14
    • 2018-12-03
    相关资源
    最近更新 更多