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}")
相关推荐
字节跳动_离青19 分钟前
智能的路径
人工智能
王上上29 分钟前
【论文阅读28】-CNN-BiLSTM-Attention-(2024)
论文阅读·人工智能·cnn
Channing Lewis40 分钟前
如果科技足够发达,是否还需要维持自然系统(例如生物多样性)中那种‘冗余’和‘多样性’,还是可以只保留最优解?
大数据·人工智能·科技
禺垣41 分钟前
区块链技术概述
大数据·人工智能·分布式·物联网·去中心化·区块链
IT科技那点事儿1 小时前
引领AI安全新时代 Accelerate 2025北亚巡展·北京站成功举办
人工智能·安全
新智元1 小时前
美 IT 业裁员狂飙 35%,「硅谷梦」彻底崩塌!打工人怒喷 PIP
人工智能·openai
新智元1 小时前
乔布斯挚友去世!胰腺癌再夺硅谷天才,曾写下苹果「创世代码」
人工智能·openai
春末的南方城市1 小时前
中山大学&美团&港科大提出首个音频驱动多人对话视频生成MultiTalk,输入一个音频和提示,即可生成对应唇部、音频交互视频。
人工智能·python·深度学习·计算机视觉·transformer
春末的南方城市1 小时前
Ctrl-Crash 助力交通安全:可控生成逼真车祸视频,防患于未然
人工智能·计算机视觉·自然语言处理·aigc·音视频
程序边界1 小时前
全球人工智能技术大会(GAITC 2025):技术前沿与产业融合的深度交响
人工智能