当前位置: 首页 > article >正文

CNN模型对CIFAR-10中的图像进行分类

代码功能

这段代码展示了如何使用 Keras 和 TensorFlow 构建一个卷积神经网络(CNN)模型,用于对 CIFAR-10 数据集中的图像进行分类。主要功能包括:
加载数据:从 CIFAR-10 数据集加载训练和测试图像。
数据预处理:将图像像素值归一化并对标签进行 one-hot 编码。
构建模型:搭建包含卷积层、池化层和全连接层的 CNN 模型。
训练模型:使用 Adam 优化器对模型进行训练。
评估模型:在测试数据集上评估模型的分类准确率。
在这里插入图片描述

代码

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}")


http://www.kler.cn/news/331692.html

相关文章:

  • 《C++20:编程世界的新变革与应用场景探索》
  • go语言种的常用排序方法
  • 力扣(leetcode)每日一题 699 掉落的方块 | 线段树|经典
  • MFC工控项目实例二十一型号选择界面删除参数按钮禁用切换
  • Python知识点:如何使用TensorFlow Lite与Python进行边缘AI计算
  • 【网络】网络安全概述
  • 探索未来:mosquitto-python,AI领域的新宠
  • ARM Process state -- SPSR
  • 滚雪球学MySQL[5.3讲]:数据库隔离级别与一致性详解:从幻读到MVCC
  • 数据结构(二叉树)
  • 基于SpringBoot+Vue的汽车保险理赔系统
  • WDG看门狗在stm32中的应用
  • 在 VSCode IDE 中,使用 ESP32-S3 的 USB 接口进行调试
  • ElasticSearch备考 -- 异步检索
  • Node.js env 环境变量多种配置方式
  • 软件测试学习笔记丨Pytest 学习指南
  • unity 默认渲染管线材质球的材质通道,材质球的材质通道
  • 学习docker第二弹------基本命令[帮助启动类命令、镜像命令、容器命令]
  • [深度学习][python]yolov11+deepsort+pyqt5实现目标追踪
  • 28 Vue3之搭建公司级项目规范