CNN模型对CIFAR-10中的图像进行分类

代码功能

这段代码展示了如何使用 Keras 和 TensorFlow 构建一个卷积神经网络(CNN)模型,用于对 CIFAR-10 数据集中的图像进行分类。主要功能包括:

加载数据:从 CIFAR-10 数据集加载训练和测试图像。

数据预处理:将图像像素值归一化并对标签进行 one-hot 编码。

构建模型:搭建包含卷积层、池化层和全连接层的 CNN 模型。

训练模型:使用 Adam 优化器对模型进行训练。

评估模型:在测试数据集上评估模型的分类准确率。

代码

python 复制代码
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical

# 加载 CIFAR-10 数据集
(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()

# 数据预处理:归一化像素值和对标签进行 one-hot 编码
train_images = train_images.astype('float32') / 255.0
test_images = test_images.astype('float32') / 255.0
train_labels = to_categorical(train_labels, 10)
test_labels = to_categorical(test_labels, 10)

# 搭建卷积神经网络模型
model = models.Sequential()

# 第一个卷积层和池化层
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))

# 第二个卷积层和池化层
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))

# 第三个卷积层和池化层
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))

# 全连接层
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))

# 编译模型
model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

# 训练模型
model.fit(train_images, train_labels, epochs=10, batch_size=64, validation_data=(test_images, test_labels))

# 评估模型
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f"Test accuracy: {test_acc:.4f}")
相关推荐
卷福同学5 分钟前
【养虾日记】Openclaw操作浏览器自动化发文
人工智能·后端·算法
春日见34 分钟前
如何入门端到端自动驾驶?
linux·人工智能·算法·机器学习·自动驾驶
光锥智能41 分钟前
从自动驾驶到 AI 能力体系,元戎启行 GTC 发布基座模型新进展
人工智能
luoganttcc42 分钟前
自动驾驶 世界模型 有哪些
人工智能·机器学习·自动驾驶
禁默1 小时前
光学与机器视觉:解锁“机器之眼”的核心密码-《第五届光学与机器视觉国际学术会议(ICOMV 2026)》
人工智能·计算机视觉·光学
深小乐1 小时前
不是DeepSeek V4!这两个神秘的 Hunter 模型竟然来自小米
人工智能
laozhao4321 小时前
科大讯飞中标教育管理应用升级开发项目
大数据·人工智能
rainbow7242441 小时前
AI人才简历评估选型:技术面试、代码评审与项目复盘的综合运用方案
人工智能·面试·职场和发展
张张123y1 小时前
RAG从0到1学习:技术架构、项目实践与面试指南
人工智能·python·学习·面试·架构·langchain·transformer
星爷AG I2 小时前
14-12 动作序列学习(AGI基础理论)
人工智能·学习·agi