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}")
相关推荐
小袁进化之路几秒前
黎跃春深度解析:2026 智能体应用开发全流程与工程化实战思路
人工智能·智能体
安如衫1 分钟前
从 OCR 到多模态 VLM Agentic AI:智能文档问答的范式转移全解
人工智能·ocr·agent·cv·rag·vlm
AI街潜水的八角2 分钟前
YOLO26手势识别项目实战1-十种手语实时检测系统数据集说明(含下载链接)
人工智能·深度学习·神经网络·yolo
康康的AI博客2 分钟前
2026 OpenAI技术全景:GPT-5.2领衔的AI革命与DMXAPI无缝替代方案
人工智能·gpt
PPIO派欧云6 分钟前
PPIO 上线 DeepSeek-OCR-2 ,支持一键私有化部署
人工智能·ocr
tamide40096698917 分钟前
云南专业AIGEO搜索优化,解锁本地流量新密码
人工智能·aigc
2501_9476941820 分钟前
易直聘受邀出席重庆人才研究和人力资源服务协会会员代表大会,赋能企业促就业
大数据·人工智能
传说故事25 分钟前
【论文自动阅读】ActiveVLA: 将主动感知注入VLA模型以实现精准三维机器人操控
人工智能·深度学习·机器人·具身智能·vla
十六年开源服务商26 分钟前
AI客服系统WordPress集成指南
人工智能
小袁进化之路27 分钟前
黎跃春讲 AI 智能体运营工程师:从工程架构到可运营系统的完整实战详解
大数据·人工智能·架构