用Python进行AI数据分析进阶教程60:
关键词:深度学习、神经网络、卷积神经网络、自然语言处理、自动驾驶
摘要:本文概述了深度学习的发展历程及其应用领域。从20世纪40年代的神经网络起源,到80年代反向传播算法的提出,再到21世纪初因数据爆炸和计算能力提升而复兴,深度学习经历了多个重要阶段。如今,各种深度学习模型如卷积神经网络(CNN)、循环神经网络(RNN)及其变体(LSTM、GRU)、生成对抗网络(GAN)等在计算机视觉、自然语言处理、语音识别及自动驾驶等领域广泛应用。文章也指出了深度学习面临的挑战,包括数据隐私、模型泛化能力和计算资源需求等问题,并通过代码示例展示了如何使用Keras实现简单的图像分类和文本分类任务。
欢迎订阅
《用Python进行AI数据分析进阶教程》专栏
《AI大模型应用实践进阶教程》专栏
《Python编程知识集锦》专栏
《字节跳动旗下AI制作抖音视频》专栏
《智能辅助驾驶》专栏
《工具软件及IT技术集锦》专栏
1、关键点
2、注意点
3、举例:
4、代码示例(使用 Keras 实现简单的 CNN 进行图像分类)
Python脚本
# 导入 TensorFlow 库,它是一个广泛使用的深度学习框架
import tensorflow as tf
# 从 TensorFlow 的 Keras 模块中导入 layers 和 models 子模块
# layers 包含各种神经网络层,如卷积层、全连接层等
# models 用于构建和管理神经网络模型
from tensorflow.keras import layers, models
# 从 TensorFlow 的 Keras 数据集模块中导入 cifar10 数据集
# CIFAR - 10 是一个常用的图像分类数据集,
# 包含 10 个不同类别的 60000 张 32x32 彩色图像
from tensorflow.keras.datasets import cifar10
# 从 TensorFlow 的 Keras 工具模块中导入 to_categorical 函数
# 该函数用于将整数标签转换为 one - hot 编码
from tensorflow.keras.utils import to_categorical
# 从 TensorFlow 的 Keras 图像预处理模块中导入 ImageDataGenerator 类
# 用于对图像数据进行增强和生成批量数据
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# 从 TensorFlow 的 Keras 回调函数模块中
# 导入 EarlyStopping 和 ModelCheckpoint 类
# EarlyStopping 用于在模型性能不再提升时提前停止训练
# ModelCheckpoint 用于在训练过程中保存模型的最佳权重
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
# 导入 matplotlib 库的 pyplot 模块,用于绘制图表和可视化数据
import matplotlib.pyplot as plt
# 加载 CIFAR - 10 数据集
# train_images 是训练集的图像数据,train_labels 是训练集的标签
# test_images 是测试集的图像数据,test_labels 是测试集的标签
(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()
# 数据预处理
# 将图像数据的像素值从 [0, 255] 范围归一化到 [0, 1] 范围,有助于模型更快收敛
train_images, test_images = train_images / 255.0, test_images / 255.0
# 将训练集和测试集的标签转换为 one - hot 编码,方便模型进行分类任务
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
# 数据增强
# 创建一个 ImageDataGenerator 对象,用于对训练图像进行数据增强
# rotation_range=20 表示随机旋转图像的角度范围为 - 20 到 20 度
# width_shift_range=0.2 表示随机水平平移图像的范围为图像宽度的 20%
# height_shift_range=0.2 表示随机垂直平移图像的范围为图像高度的 20%
# horizontal_flip=True 表示随机水平翻转图像
datagen = ImageDataGenerator(
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True
)
# 让 ImageDataGenerator 对象适应训练图像数据,计算相关统计信息
datagen.fit(train_images)
# 构建 CNN 模型
# 创建一个 Sequential 模型,它是一种线性堆叠的模型结构
model = models.Sequential()
# 添加一个二维卷积层,32 个卷积核,卷积核大小为 3x3,激活函数为 ReLU
# input_shape=(32, 32, 3) 表示输入图像的形状为 32x32 的彩色图像(3 个通道)
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
# 添加一个最大池化层,池化窗口大小为 2x2,用于减少特征图的尺寸
model.add(layers.MaxPooling2D((2, 2)))
# 再添加一个二维卷积层,64 个卷积核,卷积核大小为 3x3,激活函数为 ReLU
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# 再次添加一个最大池化层,池化窗口大小为 2x2
model.add(layers.MaxPooling2D((2, 2)))
# 又添加一个二维卷积层,64 个卷积核,卷积核大小为 3x3,激活函数为 ReLU
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# 添加一个 Flatten 层,将多维的特征图展平为一维向量
model.add(layers.Flatten())
# 添加一个 Dropout 层,丢弃率为 0.5,用于防止过拟合
# 在训练过程中,随机丢弃 50% 的神经元,减少神经元之间的依赖
model.add(layers.Dropout(0.5))
# 添加一个全连接层,64 个神经元,激活函数为 ReLU
model.add(layers.Dense(64, activation='relu'))
# 添加一个输出层,10 个神经元,激活函数为 softmax
# 用于对 10 个类别进行分类,softmax 函数将输出转换为概率分布
model.add(layers.Dense(10, activation='softmax'))
# 编译模型
# 使用 adam 优化器,它是一种自适应学习率的优化算法
# 损失函数为 categorical_crossentropy,适用于多分类问题
# 评估指标为准确率(accuracy)
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 定义回调函数
# 创建一个 EarlyStopping 回调对象,监控验证集的损失(val_loss)
# patience=3 表示如果验证集损失在连续 3 个 epoch 中没有改善,则提前停止训练
early_stopping = EarlyStopping(monitor='val_loss', patience=3)
# 创建一个 ModelCheckpoint 回调对象,监控验证集的准确率(val_accuracy)
# save_best_only=True 表示只保存验证集准确率最高的模型权重,保存为 'best_model.h5' 文件
model_checkpoint = ModelCheckpoint('best_model.h5', (
monitor='val_accuracy', save_best_only=True))
# 训练模型
# 使用 fit 方法训练模型
# datagen.flow(train_images, train_labels, batch_size = 32) 表示从增强后的训练数据中
# 生成批量数据,每个批量包含 32 个样本
# epochs = 20 表示训练 20 个 epoch
# validation_data=(test_images, test_labels) 表示使用测试集作为验证集
# callbacks=[early_stopping, model_checkpoint] 表示使用定义的回调函数
history = model.fit(datagen.flow(train_images, train_labels, batch_size=32),
epochs=20,
validation_data=(test_images, test_labels),
callbacks=[early_stopping, model_checkpoint])
# 评估模型
# 使用 evaluate 方法在测试集上评估模型,返回测试集的损失和准确率
test_loss, test_acc = model.evaluate(test_images, test_labels)
# 打印测试集的准确率
print(f"Test accuracy: {test_acc}")
# 可视化训练过程
# 创建一个大小为 12x4 英寸的图形窗口
plt.figure(figsize=(12, 4))
# 绘制损失曲线
# 在图形窗口的第一个子图中绘制训练损失和验证损失曲线
plt.subplot(1, 2, 1)
# 绘制训练损失曲线,标签为 'Training Loss'
plt.plot(history.history['loss'], label='Training Loss')
# 绘制验证损失曲线,标签为 'Validation Loss'
plt.plot(history.history['val_loss'], label='Validation Loss')
# 设置子图的标题为 'Training and Validation Loss'
plt.title('Training and Validation Loss')
# 设置 x 轴的标签为 'Epochs'
plt.xlabel('Epochs')
# 设置 y 轴的标签为 'Loss'
plt.ylabel('Loss')
# 显示图例
plt.legend()
# 绘制准确率曲线
# 在图形窗口的第二个子图中绘制训练准确率和验证准确率曲线
plt.subplot(1, 2, 2)
# 绘制训练准确率曲线,标签为 'Training Accuracy'
plt.plot(history.history['accuracy'], label='Training Accuracy')
# 绘制验证准确率曲线,标签为 'Validation Accuracy'
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
# 设置子图的标题为 'Training and Validation Accuracy'
plt.title('Training and Validation Accuracy')
# 设置 x 轴的标签为 'Epochs'
plt.xlabel('Epochs')
# 设置 y 轴的标签为 'Accuracy'
plt.ylabel('Accuracy')
# 显示图例
plt.legend()
# 显示绘制好的图形
plt.show()
测试集评估输出
plaintext
Test accuracy: 0.7234
可视化结果
运行代码后会弹出一个窗口,显示两个子图。
重点语句解读
1、关键点
2、注意点
3、举例:
4、代码示例(使用 Keras 实现简单的 LSTM 进行文本分类)
Python脚本
# 导入 TensorFlow 库,它是一个强大的深度学习框架,用于构建和训练神经网络模型
import tensorflow as tf
# 从 TensorFlow 的 Keras 模块的 datasets 子模块中导入 imdb 数据集
# imdb 是一个经典的影评数据集,用于文本分类任务
from tensorflow.keras.datasets import imdb
# 从 TensorFlow 的 Keras 模块的 preprocessing 子模块中导入 sequence 工具
# 该工具可用于对序列数据进行预处理,如填充和截断
from tensorflow.keras.preprocessing import sequence
# 从 TensorFlow 的 Keras 模块的 models 子模块中导入 Sequential 类
# Sequential 类用于构建顺序模型,即层按顺序依次堆叠的模型
from tensorflow.keras.models import Sequential
# 从 TensorFlow 的 Keras 模块的 layers 子模块中导入 Embedding、LSTM 和 Dense 层
# Embedding 层用于将整数编码的词汇转换为密集向量表示
# LSTM 是长短期记忆网络层,适用于处理序列数据
# Dense 是全连接层,用于对输入进行线性变换和非线性激活
from tensorflow.keras.layers import Embedding, LSTM, Dense
# 从 TensorFlow 的 Keras 模块的 callbacks 子模块中
# 导入 EarlyStopping 和 ModelCheckpoint 类
# EarlyStopping 用于在模型训练过程中,当监测的指标(如验证损失)不再改善时提前停止训练
# ModelCheckpoint 用于在训练过程中保存模型的权重,可根据指定的指标保存最佳模型
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
# 导入 matplotlib 库的 pyplot 模块,用于绘制图表,可视化训练过程中的损失和准确率
import matplotlib.pyplot as plt
# 创建保存模型的目录(如果不存在)
import os
os.makedirs('models', exist_ok=True)
# 设置参数
# max_features 表示只考虑数据集中出现频率最高的前 10000 个单词
max_features = 10000
# maxlen 表示每个影评序列的最大长度,超过该长度的序列将被截断,不足的将被填充
maxlen = 200
# 加载 IMDB 影评数据集
# num_words 参数指定只使用前 max_features 个单词
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
# 数据预处理
# 使用 sequence.pad_sequences 函数对训练集的影评序列进行填充或截断
# maxlen 参数指定序列的最大长度,确保所有序列长度一致
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
# 构建 LSTM 模型
model = Sequential()
# 添加 Embedding 层
model.add(Embedding(input_dim=max_features, output_dim=128))
# 添加 LSTM 层,使用 dropout 和 recurrent_dropout 防止过拟合
model.add(LSTM(units=128, dropout=0.2, recurrent_dropout=0.2))
# 添加输出层,使用 sigmoid 激活函数进行二分类
model.add(Dense(units=1, activation='sigmoid'))
# 编译模型
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
# 打印模型结构(可选)
model.summary()
# 定义回调函数
early_stopping = EarlyStopping(monitor='val_loss', patience=3)
model_checkpoint = ModelCheckpoint('models/best_model.h5',
monitor='val_accuracy',
save_best_only=True)
# 训练模型
history = model.fit(x_train, y_train,
epochs=10,
batch_size=32,
validation_data=(x_test, y_test),
callbacks=[early_stopping, model_checkpoint])
# 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"Test accuracy: {test_acc:.4f}")
# 可视化训练过程
plt.figure(figsize=(12, 4))
# 绘制损失曲线
plt.subplot(1, 2, 1)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.grid(True, linestyle='--', alpha=0.6)
# 绘制准确率曲线
plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.grid(True, linestyle='--', alpha=0.6)
# 显示图形
plt.tight_layout()
plt.show()
输出 / 打印结果及注释
在训练过程中,会逐轮(epoch)输出训练信息,大致格式如下:
plaintext
Epoch 1/10
782/782 [==============================] - 13s 17ms/step - loss: 0.6927 - accuracy: 0.5037 - val_loss: 0.6920 - val_accuracy: 0.5000
plaintext
Test accuracy: 0.82
运行代码后会弹出一个窗口,显示两个子图。
重点语句解读
1、关键点
2、注意点
3、举例:
1、关键点
2、注意点
3、举例:
——The END——
序号 | 专栏名称 | 说明 |
---|---|---|
1 | 用Python进行AI数据分析进阶教程 | 《用Python进行AI数据分析进阶教程》专栏 |
2 | AI大模型应用实践进阶教程 | 《AI大模型应用实践进阶教程》专栏 |
3 | Python编程知识集锦 | 《Python编程知识集锦》专栏 |
4 | 字节跳动旗下AI制作抖音视频 | 《字节跳动旗下AI制作抖音视频》专栏 |
5 | 智能辅助驾驶 | 《智能辅助驾驶》专栏 |
6 | 工具软件及IT技术集锦 | 《工具软件及IT技术集锦》专栏 |
关注我 @理工男大辉郎 获取实时更新
欢迎关注、收藏或转发。
敬请关注 我的
微信搜索公众号:cnFuJH
CSDN博客:理工男大辉郎
抖音号:31580422589