首页  >  文章  >  后端开发  >  用 Python 构建基本的卷积神经网络 (CNN)

用 Python 构建基本的卷积神经网络 (CNN)

WBOY
WBOY原创
2024-08-28 18:33:07728浏览

Building a Basic Convolutional Neural Network (CNN) in Python

卷积神经网络 (CNN) 是用于图像处理和识别任务的强大工具。它们被设计为通过反向传播自动、自适应地学习特征的空间层次结构。让我们深入研究使用 Python 和 TensorFlow/Keras 构建基本的 CNN。

?先决条件

开始之前,请确保您已安装以下库:

pip install tensorflow numpy matplotlib

?️ 第1步:导入必要的库

首先导入必要的库:

import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt

?️ 第 2 步:加载并预处理数据集

在此示例中,我们将使用 CIFAR-10 数据集,该数据集由 10 个类别的 60,000 张 32x32 彩色图像组成。

# Load the CIFAR-10 dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()

# Normalize the pixel values to be between 0 and 1
x_train, x_test = x_train / 255.0, x_test / 255.0

?第 3 步:构建 CNN 模型

现在,让我们构建 CNN 模型。该模型将包括关键层:卷积层、池化层和密集层。

model = models.Sequential()

# First Convolutional Layer
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))

# Second Convolutional Layer
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))

# Third Convolutional Layer
model.add(layers.Conv2D(64, (3, 3), activation='relu'))

# Flatten the output and add Dense layers
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))

?第四步:编译模型

编译模型涉及指定优化器、损失函数和训练期间要监控的指标。

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

?第 5 步:训练模型

在几个时期的训练数据上训练 CNN 模型。

history = model.fit(x_train, y_train, epochs=10, 
                    validation_data=(x_test, y_test))

?第 6 步:评估模型

训练后,根据测试数据评估模型,看看它的表现如何。

test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f'\nTest accuracy: {test_acc}')

?️ 第 7 步:可视化训练结果

最后,让我们可视化训练时期的准确性和损失。

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0, 1])
plt.legend(loc='lower right')
plt.show()

?结论

这个基本的 CNN 模型是处理图像分类任务的一个很好的起点。通过理解和修改此模型,您可以尝试不同的架构和技术来增强模型的性能。继续探索和调整层以构建更强大的神经网络! ?


这段代码的设计易于理解和修改,适合初学者和那些希望开始使用 Python 学习 CNN 的人。

CNN 架构的博客链接:https://dev.to/abhinowww/demystifying-cnn-neural-network-layers-a-deep-dive-into-ai-architecture-12d2

以上是用 Python 构建基本的卷积神经网络 (CNN)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn