要得到混淆矩阵,我们需要使用训练好的模型对测试数据进行预测,并将预测结果与真实标签进行比较。以下是一个示例代码,展示如何使用Keras构建CNN模型,并计算混淆矩阵。
import numpy as np
from sklearn.metrics import confusion_matrix
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from keras.utils import to_categorical
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 将数据进行预处理
x_train = x_train.reshape(-1, 28, 28, 1)
x_test = x_test.reshape(-1, 28, 28, 1)
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
# 构建CNN模型
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(10, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, batch_size=128, epochs=5, verbose=1, validation_data=(x_test, y_test))
# 使用模型进行预测
y_pred = model.predict_classes(x_test)
# 计算混淆矩阵
cm = confusion_matrix(np.argmax(y_test, axis=1), y_pred)
print(cm)
这段代码中,我们使用Keras库加载MNIST数据集,并对数据进行预处理。然后,我们构建了一个简单的CNN模型,使用训练数据进行训练。接下来,我们使用训练好的模型对测试数据进行预测,并使用sklearn库中的confusion_matrix函数计算混淆矩阵。最后,我们将混淆矩阵打印出来。
请注意,这个示例使用了x_train
、x_test
、y_train
、y_test
这些变量来存储训练和测试数据。如果你不想使用这些变量,你可以通过其他方式加载和准备数据,只要保证最后可以获得x_test
和y_test
这两个变量即可。
下一篇:不使用选取来与文档进行交互。