keras迁移学习中的混淆矩阵

时间:2020-10-18 10:43:17

标签: python keras deep-learning confusion-matrix transfer-learning

我打算在模型中绘制混淆矩阵,并使用了基于深度学习模型的转移学习概念。

混淆矩阵的代码

def plot_confusion_matrix(cm, classes, normalize=False,title='Confusion Matrix', cmap=plt.cm.Blues):
  plt.imshow(cm, interpolation='nearest', cmap=cmap)
  plt.title(title)
  plt.colorbar()
  tick_marks = np.arange(len(classes))
  plt.xticks(tick_marks, classes, rotation=45)
  plt.yticks(tick_marks, classes)

  if normalize:
    cm=cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    print("Normalized Confusion Matrix")
  else:
    print("Confusion matrix, without normalization")
  print(cm)

  thresh = cm.max() / 2
  for i, j in itertools.product(range(cm.shape[0]),range(cm.shape[1])):
    plt.text(j, i, cm[i, j],
             horizontalalignment="center",
             color="white" if cm[i,j] > thresh else "black")
  plt.tight_layout()
  plt.ylabel('True Label')
  plt.xlabel('Predicted Label')

现在在 test_labels 预测的形状下方,

test_labels.shape
(12,)
predictions.shape
(10,2)

上面的代码可以正常工作,但是我在下面看到错误。因此,请关注以下代码,

cm = confusion_matrix(test_labels, predictions.argmax(axis=1))

这是错误

ValueError                                Traceback (most recent call last)
<ipython-input-40-79fd4e2e074c> in <module>()
----> 1 cm = confusion_matrix(test_labels, predictions.argmax(axis=1))

2 frames
/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
    210     if len(uniques) > 1:
    211         raise ValueError("Found input variables with inconsistent numbers of"
--> 212                          " samples: %r" % [int(l) for l in lengths])
    213 
    214 

ValueError: Found input variables with inconsistent numbers of samples: [12, 10]
  

注意:这是值错误,对此我感到困惑,我尝试了越来越多,但失败了。因此,我需要帮助来解决此错误。

1 个答案:

答案 0 :(得分:1)

错误提示,test_labelspredictions的样本量不同。当您使用批次进行预测时可能会发生这种情况,这可能会导致最后几个样本丢失。

一种可能性是,您可以使用:

cm = confusion_matrix(test_labels[:-2], predictions.argmax(axis=1))

这可以解决形状不匹配的问题(但这是基于预测中缺少最后两个样本的假设)。

如果您可以共享用于预测的代码,我也许可以提供更有用的答案。