Python中的卷积神经网络(CNN)入门

卷积神经网络(Convolutional Neural Networks, CNN)是一类特别适用于处理图像数据的深度学习模型。在Python中,我们可以使用流行的深度学习库TensorFlow和Keras来创建和训练一个CNN模型。在本文中,我们将介绍如何使用Keras创建一个简单的CNN模型,并用它对手写数字进行分类。

1. 准备数据集

我们将使用MNIST数据集,这是一个常用的手写数字数据集。Keras库提供了一个方便的函数来加载MNIST数据集。数据集包含60000个训练样本和10000个测试样本,每个样本是一个28x28的灰度图像。

复制代码
python
复制代码
from tensorflow.keras.datasets import mnist

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

接下来,我们需要对数据进行预处理。我们将图像数据归一化到0-1之间,并将标签数据进行one-hot编码:

复制代码
python
复制代码
train_images = train_images.reshape((60000, 28, 28, 1))
train_images = train_images.astype("float32") / 255

test_images = test_images.reshape((10000, 28, 28, 1))
test_images = test_images.astype("float32") / 255

from tensorflow.keras.utils import to_categorical

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
2. 创建CNN模型

我们将使用Keras创建一个简单的CNN模型,包括卷积层、池化层、全连接层等。模型的结构如下:

  • 卷积层:使用32个3x3的卷积核,激活函数为ReLU;

  • 池化层:使用2x2的最大池化;

  • 卷积层:使用64个3x3的卷积核,激活函数为ReLU;

  • 池化层:使用2x2的最大池化;

  • 全连接层:包含128个神经元,激活函数为ReLU;

  • 输出层:包含10个神经元,激活函数为softmax。

    python
    复制代码
    from tensorflow.keras import layers
    from tensorflow.keras import models

    model = models.Sequential()
    model.add(layers.Conv2D(32, (3, 3), activation="relu", input_shape=(28, 28, 1)))
    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(128, activation="relu"))
    model.add(layers.Dense(10, activation="softmax"))

3. 训练CNN模型

我们将使用训练数据集训练CNN模型,并在测试数据集上评估模型性能。我们将使用交叉熵损失函数和Adam优化器,训练10个epoch。

复制代码
python
复制代码
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])

model.fit(train_images, train_labels, epochs=10, batch_size=64)

test_loss, test_acc = model.evaluate(test_images, test_labels)
print("Test accuracy: {:.2f}%".format(test_acc * 100))
4. 使用CNN模型进行预测

训练好CNN模型后,我们可以用它对新的图像数据进行预测。下面我们将随机选择一个测试图像,并使用模型进行预测。

复制代码
python
复制代码
import numpy as np
import matplotlib.pyplot as plt

index = np.random.randint(0, len(test_images))
image = test_images[index]

plt.imshow(image.reshape(28, 28), cmap="gray")
plt.show()

predictions = model.predict(np.expand_dims(image, axis=0))
predicted_label = np.argmax(predictions)

print("Predicted label:", predicted_label)

上述代码将展示一个随机选择的手写数字图像,并输出模型预测的结果。

这就是如何在Python中使用Keras创建和训练一个简单的CNN模型进行手写数字分类。在实际应用中,可以根据需求调整CNN模型的结构和参数以优化性能。

相关推荐
动词ing11 分钟前
【C语言】结构体+文件基础
c语言·开发语言·数据结构
H03111698512 分钟前
择校参考:枫叶教育 vs 大连美国国际学校,外籍子女学校怎么选
人工智能
caimouse27 分钟前
ReactOS 窗口系统分析(7):分层窗口与绘制辅助 — layered.c + draw.c
c语言·开发语言
刘海东刘海东35 分钟前
一条新的人工智能道路(刘海东)一、二、三章
人工智能
xyz_CDragon43 分钟前
从 RTL 到 GDSII:人与 AI 协作,用开源 EDA 工具链完成 SHA-256 芯片的 SoC 集成与签核全流程(附完整流程+代码)
人工智能·开源·芯片设计·开源 eda·caravel
丰锋ff1 小时前
基于 Qt 的智慧社区物业管理系统
开发语言·qt
咕咕AI学堂1 小时前
检索引擎深度对比:Elasticsearch vs Milvus vs Redis 在 RAG 中的定位
人工智能
Java牛马1 小时前
AI Agent 技术栈梳理(Skill / 蒸馏 / MCP / Harness)
人工智能·ai agent·蒸馏·skill·mcp·harness
夜不会漫长1 小时前
C++入门(1)
开发语言·c++·算法
IT_陈寒1 小时前
Vue的computed属性把我坑惨了,原来我一直用错姿势
前端·人工智能·后端