从 CNN 模型绘制混淆矩阵

Plot Confusion Matrix from CNN Model

此原创作品呈现here

如何绘制基于 CNN 模型的混淆矩阵?

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.optimizers import Adam
from keras.utils import np_utils
from sklearn import metrics 

##Need to put this block of code in for cuDNN to initialize properly
import tensorflow as tf
config = tf.compat.v1.ConfigProto(gpu_options = tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.8)
# device_count = {'GPU': 1}
)
config.gpu_options.allow_growth = True
session = tf.compat.v1.Session(config=config)
tf.compat.v1.keras.backend.set_session(session)
#------------------------------------------------------------------------------------------------------------------
num_rows = 40
num_columns = 174
num_channels = 1

x_train = x_train.reshape(x_train.shape[0], num_rows, num_columns, num_channels)
x_test = x_test.reshape(x_test.shape[0], num_rows, num_columns, num_channels)

num_labels = yy.shape[1]
filter_size = 2

# Construct model 
model = Sequential()
model.add(Conv2D(filters=16, kernel_size=2, input_shape=(num_rows, num_columns, num_channels), activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.2))

model.add(Conv2D(filters=32, kernel_size=2, activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.2))

model.add(Conv2D(filters=64, kernel_size=2, activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.2))

model.add(Conv2D(filters=128, kernel_size=2, activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.2))
model.add(GlobalAveragePooling2D())

model.add(Dense(num_labels, activation='softmax'))

然后训练为:

from keras.callbacks import ModelCheckpoint 
from datetime import datetime 

#num_epochs = 12
#num_batch_size = 128

num_epochs = 72
num_batch_size = 256

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.basic_cnn.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(x_train, y_train, batch_size=num_batch_size, epochs=num_epochs, validation_data=(x_test, y_test), callbacks=[checkpointer], verbose=1)

我一直在尝试一些事情,其中​​之一是:

import matplotlib.pyplot as plt

plt.figure(figsize=(12, 4))
plot_confusion_matrix=(model(),x_test, y_test)
plt.plot(plot_confusion_matrix)

但我无法绘制混淆矩阵。

我也看了tf.math.confusion_matrix(),但是上面CNN模型定义的labelspredictions是什么??

混淆矩阵是多分类的。

y_true = np.argmax(y_test, 1)??

y_pred = model.predict_classes(x_test)??

labels:用于分类任务的真实标签的一维张量。 预测:给定分类的预测的一维张量。

正如他们在官方文档中所说,标签是输出 类 和预测的名称,但是正如他们所说的一切都必须是一维张量,这意味着标签将是一个实例的基本事实和相应的索引Predictions 中的 value 将保持其预测值。 所以你可以做的是,获取每个实例的预测和标签,在你的代码中,你已经传递了 x_test 和 y_test 这不是应该传递的元素。 而是使用 model.predict 来获取输出标签。

y_predict=model.predict(x_test)
y_true=y_test
res = tf.math.confusion_matrix(y_true,y_predict)

这个 res 是一个二维矩阵,现在你需要打印它

 plot_confusion_matrix(classifier, X_test, y_test,
                             display_labels=class_names,
                             cmap=plt.cm.Blues,
                             normalize=normalize)

这里放的是classifer = "model",不是functional model()。 希望这对您有所帮助,这里有更多资源。

Multiclass plot github function

Another custom plot function