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}")
相关推荐
小程故事多_808 小时前
Agent+Milvus,告别静态知识库,打造具备动态记忆的智能AI助手
人工智能·深度学习·ai编程·milvus
code_pgf8 小时前
Llama 3详解
人工智能·llama
ComputerInBook8 小时前
数字图像处理(4版)——第 3 章——(图像的)强度变换和空间滤波(Rafael C.Gonzalez&Richard E. Woods)
图像处理·人工智能·计算机视觉·强度变换和空间滤波
爱写代码的小朋友8 小时前
生成式人工智能(AIGC)在开放式教育问答系统中的知识表征与推理机制研究
人工智能·aigc
技术专家8 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
m0_488913018 小时前
万字长文带你梳理Llama开源家族:从Llama-1到Llama-3,看这一篇就够了!
人工智能·学习·机器学习·大模型·产品经理·llama·uml
helpme流水8 小时前
LLaMA Factory 从入门到精通,一篇讲完
人工智能·ai·语言模型·llama
段一凡-华北理工大学8 小时前
【大模型+知识图谱+工业智能体技术架构】~系列文章01:快速了解与初学入门!!!
人工智能·python·架构·知识图谱·工业智能体
Swift社区8 小时前
AI Governance:从 Policy Engine 到完整治理体系
人工智能·openclaw
田井中律.8 小时前
知识图谱(BILSTM+CRF项目完整实现)【第六章】
人工智能·知识图谱