首页 > 解决方案 > keras 迁移学习中的混淆矩阵

问题描述

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

混淆矩阵的代码

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]
  

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

标签: pythonkerasdeep-learningconfusion-matrixtransfer-learning

解决方案


test_labels正如错误所暗示的,对于和,您有不同的样本量predictions。当您使用批次进行预测时可能会发生这种情况,这可能会导致最后几个样本的丢失。

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

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

这可能会解决形状不匹配问题(但它是基于最后两个样本在预测中丢失的假设)。

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


推荐阅读