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

相关推荐
2601_9679801137 分钟前
深入理解词向量算法及其在Python中的实践
python·word2vec·glove·fasttext·词向量
129Lab1 小时前
电池循环测试数据自动化分析:用Python+AI工具构建一键式寿命评估流水线
python·数据分析·电池测试·数据自动化·寿命评估
treasure1401 小时前
【复古】浅尝Django前后端不分离
前端·css·python·django·bootstrap·html·web
老金带你玩AI1 小时前
惊人的一致性!Seedream 5.5实测!
人工智能
Dmz丶2 小时前
前端转 AI 100 天 Day 44:前端集成实战——用 React 给 Agent 做个正式界面
python
数据技术说2 小时前
在 KES AI 数据库上搭一条 NL2SQL 链路:语义、召回、权限各放哪
人工智能·sql·代码规范
jay神2 小时前
基于 YOLOv8 的手势识别系统(Web 版)
前端·人工智能·python·深度学习·yolo·计算机视觉·计算机毕业设计
奶油话梅糖2 小时前
用 iPhone 扫一间房,AI 帮你在浏览器里 1:1 重建它:Wes Bos 的 scan-to-threejs 工作流
人工智能·ios·iphone
DeepVisionary2 小时前
阿里云上线旗舰多模态新模型,不公布跑分且限时14天退役
python·自动化
东莞市云毅网络有限公司2 小时前
FAQ 覆盖度打分:TF-IDF 与向量嵌入双路召回的 Python 实现
python·数据清洗·rag·企业知识库·文档解析