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模型的结构和参数以优化性能。

相关推荐
CodeYp20191 分钟前
第6讲:模板初阶
开发语言·c++·模板
2601_960631233 分钟前
从中药产线技改备案细节,看传统药企的“专精特新”路径
人工智能
SEO_juper5 分钟前
Node.js 全站死链检测工具:从 sitemap 出发一次找全 404
开发语言·人工智能·python·node.js·seo·外贸独立站
张彦峰ZYF8 分钟前
让 Agent 获得“手、脚与反射弧”: MHS 如何重构物理世界的长程自主化基础设施
人工智能·ai agent·mhs·可复用能力·治理、记忆、持久编排·工具路由和物理执行·长程agent五平面架构
ljt27249606619 分钟前
Python笔记(九)--asyncio
笔记·python
AI棒棒牛10 分钟前
基于 IDEAL 思想的 YOLO26 双分支适配:差异证据与不确定性门控,RGB+IR双分支创新!
人工智能·深度学习·yolo·目标检测·yolo26
xiongmosy13 分钟前
声网创始人兼CEO赵斌:对话AGI的终点,是“理解一个人”
人工智能·agi
瓶瓶持续学习中14 分钟前
数字孪生到空间智能,5家厂商的技术路线有何不同?
大数据·人工智能·信息可视化·架构
neocheng_52217 分钟前
不能固定时间上课,可以考哪些AI证书?
人工智能