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}")
相关推荐
爱吃泡芙的小白白2 分钟前
深入浅出:卷积神经网络(CNN)池化层全解析——从MaxPool到前沿发展
人工智能·神经网络·cnn·池化层·最大值池化·平均值池化
jigsaw_zyx8 分钟前
提示词工程
人工智能·算法
jdyzzy11 分钟前
什么是 JIT 精益生产模式?它与传统的生产管控方式有何不同?
java·大数据·人工智能·jit
LittroInno13 分钟前
TVMS视频管理平台 —— 多种目标跟踪模式
人工智能·计算机视觉·目标跟踪
查无此人byebye19 分钟前
突破性图像分词技术TiTok:32个Token实现高效图像重建与生成
人工智能
Niuguangshuo19 分钟前
DALL-E 2:从CLIP潜变量到高质量图像生成的突破
人工智能·深度学习·transformer
偷吃的耗子19 分钟前
【CNN算法理解】:基于训练好的MNIST CNN模型进行预测
人工智能·算法·cnn
Elastic 中国社区官方博客19 分钟前
跳过 MLOps:通过 Cloud Connect 使用 EIS 为自管理 Elasticsearch 提供托管云推理
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
北京耐用通信24 分钟前
耐达讯自动化Profinet转Devicenet网关:精细化工行业的“协议融合利器”
人工智能·物联网·网络协议·自动化·信息与通信
做萤石二次开发的哈哈30 分钟前
萤石云广播:智能语音广播,一键文字下发
人工智能·语音识别