Python - 混淆矩阵维度的差异

时间:2018-03-13 22:22:23

标签: python machine-learning scikit-learn classification confusion-matrix

我对混淆矩阵有疑问。我使用交叉验证来分割148个实例,用于两个数组 - 测试和训练。比我打电话的那样:

def GenerateResult:
   clf = OneVsRestClassifier(GaussianNB())
   clf.fit(x_train, y_train)
   predictions = clf.predict(x_test)
   accuracy = accuracy_score(y_test, predictions)
   confusion_mtrx = confusion_matrix(y_test, predictions)

这是KFold的循环 - >我从上面调用函数:

for train_idx, test_idx in pf.split(x_array):
       x_train, x_test = x_array[train_idx], x_array[test_idx]
       y_train, y_test = y_array[train_idx], y_array[test_idx]
       acc, confusion= GenerateResult(x_train, x_test, y_train, y_test)
       results['First'].append(acc)
       confusion_dict['First'].append(confusion)

然后我总结结果并计算平均值

np_gausian = np.asarray(results['gaussian'])
print("[First] Mean: {}".format(np.mean(np_gausian)))

print(confusion_dict['gaussian'])

我有一个问题。在我的148个实例中,我在输出中有4个类,当我将该循环用于KFold时,我得到了两个不同的混淆矩阵。 第一个混淆矩阵3x3:

[[36  1  1]

 [15 17  1]

 [ 0  0  3]]

第二次4x4:

[[ 0  2  0  0]

 [ 0 41  2  0]

 [ 0 12 16  0]

 [ 0  0  1  0]]

我认为我有一个问题因为我的148实例

  • Class 1 - 2 ea

  • 第2类 - 81 ea

  • Class 3 - 61 ea

  • 4 - 4级

  • 所有班级 - 148

我该怎么办?我如何总结这种混淆矩阵?如果我更改KFold的分割数量该怎么办?我尝试使用熊猫,但我不知道该怎么做。请帮助,我使用sk-learn for it

1 个答案:

答案 0 :(得分:0)

正如@KRKirov在评论中所指出的,其原因是由于Kfold交叉验证将数据拆分为折叠,因此在该折叠的测试集中不存在某些类。

例如,如果{1}中没有class1,y_test中也没有预测,那么predictions代码会自动推断出数据中只有三个类并根据它生成矩阵。

您可以通过设置labels param强制confusion_matrix使用所有类: -

  

标签:数组,形状= [n_classes],可选

confusion_matrix

通过这样做:

List of labels to index the matrix. This may be used to reorder or
select a subset of labels. If none is given, those that appear at
least once in y_true or y_pred are used in sorted order.

您需要将y_array或y_array中的唯一标签传递给GenerateResult()方法。

相关问题