深度学习卷积神经网络进行图片分类,并计算模型准确率,用混淆矩阵工具对模型分类结果进行分析的完整代码
时间: 2024-10-09 12:14:52 浏览: 42
深度学习卷积神经网络(Convolutional Neural Networks, CNN)用于图像分类是一种常见的机器学习应用。这里是一个简单的例子,使用Python和TensorFlow库来构建一个CNN模型,训练数据集来自Keras的数据集(如MNIST),并使用sklearn库计算模型准确率以及混淆矩阵。
```python
# 导入所需库
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from sklearn.metrics import accuracy_score, confusion_matrix
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255
x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
# 构建模型
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=10, validation_split=0.1)
# 预测测试集
predictions = model.predict_classes(x_test)
# 计算准确率
accuracy = accuracy_score(y_test.argmax(axis=-1), predictions)
print(f"模型准确率:{accuracy * 100}%")
# 计算混淆矩阵
cm = confusion_matrix(y_test.argmax(axis=-1), predictions)
print("混淆矩阵:")
print(cm)
```
阅读全文