我的CNN模型运行后,我一直试图运行一个混淆矩阵。

我的模型是对狗/兔子进行分类。

以下是我所做的:

我将每个班级(狗/婴儿)的照片放在两个文件夹中的单独文件夹中:培训和测试。

培训目录->兔子目录->兔子图像

训练目录->小狗目录->小狗图像

测试目录->兔子目录->兔子图像

测试目录->小狗目录->小狗图像

我使用以下代码从文件夹中获取图像:

training_data = train_datagen.flow_from_directory('./images/train',
                                             target_size = (28, 28),
                                             batch_size = 86,
                                             class_mode = 'binary',
                                             color_mode='rgb',
                                             classes=None)


test_data = test_datagen.flow_from_directory('./images/test',
                                        target_size = (28, 28),
                                        batch_size = 86,
                                        class_mode = 'binary',
                                        color_mode='rgb',
                                        classes=None)


我使用以下代码将图像分离为训练/验证。

data_generator = ImageDataGenerator(
    validation_split=0.2,
    rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
)

train_generator = data_generator.flow_from_directory(
    './images/train',
    target_size = (28, 28),
    batch_size = 86,
    class_mode = 'binary',
    color_mode='rgb',
    classes=None, subset="training"
)

validation_generator = data_generator.flow_from_directory(
    './images/train',
    target_size = (28, 28),
    batch_size = 86,
    class_mode = 'binary',
    color_mode='rgb',
    classes=None, subset="validation"
)

history=classifier.fit_generator(
    train_generator,
    steps_per_epoch = (8000 / 86),
    epochs = 2,
    validation_data = validation_generator,
    validation_steps = 8000/86,
    callbacks=[learning_rate_reduction]
)


当我尝试运行confusion_matrix(validation_data)时,出现以下错误:

TypeError: confusion_matrix() missing 1 required positional argument: 'y_pred'

当我跑步时

#Confusion matrix
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    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]

    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')

# Predict the values from the validation dataset
Y_pred = classifier.predict(training_data)
# Convert predictions classes to one hot vectors
Y_pred_classes = np.argmax(Y_pred,axis = 1)
# Convert validation observations to one hot vectors
Y_true = np.argmax(training_data,axis = 1)
# compute the confusion matrix
confusion_mtx = confusion_matrix(Y_true, Y_pred_classes)
# plot the confusion matrix
plot_confusion_matrix(confusion_mtx, classes = range(10))

sns.heatmap(confusion_mtx, annot=True, fmt='d')


我收到以下错误

AttributeError: 'DirectoryIterator' object has no attribute 'ndim'

最佳答案

据我了解,您想使用混淆矩阵和热图来验证分类器模型。
我还对垃圾邮件文本分类进行了验证,因此您可以执行此操作,

对于混淆矩阵,

from sklearn.metrics import confusion_matrix
conf_mat = confusion_matrix(y_test, y_pred)
print(conf_mat)


对于热图,

import seaborn as sns
conf_mat = confusion_matrix(y_test, y_pred)
conf_mat_normalized = conf_mat.astype('float') / conf_mat.sum(axis=1)[:, np.newaxis]
sns.heatmap(conf_mat_normalized)
plt.ylabel('True label')
plt.xlabel('Predicted label')


仅仅意味着混淆矩阵需要两个参数(您的实际真相标签和预测的标签列表)

希望对您有帮助。

关于python-3.x - CNN-尝试使用seaborn.heatmap运行混淆矩阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54269849/

10-12 19:23