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}")
相关推荐
u0103055271 分钟前
Java I/O核心操作实战
人工智能·1024程序员节
QZSJTR4 分钟前
数据驱动与效果监控:泉州企业 GEO 优化的度量体系怎么搭
人工智能·ai搜索优化·geo优化
celiahul5 分钟前
当搜索引擎变成“问答机器人”,你的网站该如何适配?
网络·人工智能·搜索引擎·内容运营·外贸推广
KJ_BioMed10 分钟前
Science Advances论文复现:461个香豆素分子的虚拟筛选参数解析
人工智能·生物医药·科研干货·科晶生物·小分子药物
这就是佬们吗12 分钟前
企业Agent落地为什么需要RAG?
人工智能·python·fastapi
xqqxqxxq26 分钟前
AI Agent学习:用户记忆系统(李博杰《深入理解 AI Agent》3.1观后总结)
人工智能·学习
临床数据科学和人工智能兴趣组28 分钟前
R Markdown 如何写
人工智能·机器学习·数据分析·r语言·r语言-4.2.1
粉色大象33 分钟前
线性代数基础知识点
人工智能·线性代数·机器学习
腾讯云大数据35 分钟前
腾讯云智能数据湖计算AI DLC发布会回顾:Spark+Ray一体化,面向Agent重构数据底座
人工智能·spark·腾讯云
半兽先生40 分钟前
2026年RAG系统主流开源文档解析工具选型指南:PaddleOCR、MinerU、LiteParse、HunyuanOCR、Apache Tika 全面对比
人工智能·python·机器学习·ai·开源