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}")
相关推荐
胖头鱼的鱼缸(尹海文)20 分钟前
数据库管理-第376期 Oracle AI DB 23.26新特性一览(20251016)
数据库·人工智能·oracle
瑞禧生物ruixibio24 分钟前
4-ARM-PEG-Pyrene(2)/Biotin(2),多功能化聚乙二醇修饰荧光标记生物分子的设计与应用探索
arm开发·人工智能
大千AI助手28 分钟前
Huber损失函数:稳健回归的智慧之选
人工智能·数据挖掘·回归·损失函数·mse·mae·huber损失函数
墨利昂39 分钟前
10.17RNN情感分析实验:加载预训练词向量模块整理
人工智能·rnn·深度学习
【建模先锋】43 分钟前
一区直接写!CEEMDAN分解 + Informer-LSTM +XGBoost组合预测模型
人工智能·lstm·ceemdan·预测模型·风速预测·时间序列预测模型
fsnine1 小时前
YOLOv2原理介绍
人工智能·计算机视觉·目标跟踪
倔强的石头1061 小时前
AI修图革命:IOPaint+cpolar让废片拯救触手可及
人工智能·cpolar·iopaint
文火冰糖的硅基工坊1 小时前
[人工智能-大模型-15]:大模型典型产品对比 - 数字人
人工智能·大模型·大语言模型
JJJJ_iii1 小时前
【机器学习05】神经网络、模型表示、前向传播、TensorFlow实现
人工智能·pytorch·python·深度学习·神经网络·机器学习·tensorflow
William.csj1 小时前
服务器/Pytorch——对于只调用一次的函数初始化,放在for训练外面和里面的差异
人工智能·pytorch·python