使用门控循环单元网络生成文本

2025 年 4 月 2 日 | 阅读 6 分钟

什么是门控循环单元网络?

门控循环单元网络长短期记忆网络 (LSTM) 的一种循环神经网络替代方案。GRU 可以处理序列数据,例如文本、语音和时间序列

GRU 的核心思想是采用门控技术来选择性地更新网络在每个时间步的隐藏状态。门控机制控制着信息流入和流出网络的流量。GRU 包含两个门控机制:重置门和更新门。

问题陈述

我们将构建一个使用门控循环单元的文本生成器。我们将通过传入一个文本文件训练网络,该文件将将每个字符映射到一个唯一的数字。然后,我们将对每个字符进行热编码,将其转换为向量,网络需要用到这些向量。

我们将使用一系列著名歌手的歌词(.txt 格式)用于文本生成。

可以从 歌词 下载。

使用门控循环单元网络实现文本生成的实现方法

步骤 1:库和数据集

第一步是导入所需的库,如 numpy, tensorflow, 和 keras,以及它们的各种模型,如 LSTM, Sequential 等。然后,我们将加载并读取文本文件,并将其存储在一个字符串中。

代码

输出

Text Generation using Gated Recurrent Unit Networks

步骤 2:字符映射

读取文件后,我们将所有唯一字符存储在一个列表中。然后,我们将创建字典,将所有字符映射到索引

代码

输出

['\n', ' ', '!', '"', '&', "'", '(', ')', ',', '-', '.', ';', '?', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'Y', '[', ']', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

步骤 3:数据预处理

在获得唯一单词后,我们将预处理数据,将文本分割成最长子序列,达到最大长度,然后对每个字符进行热编码,将其转换为向量

代码

步骤 4:构建 GRU 网络

我们将创建一个顺序模型,并添加多个层,如 GRU, Dense, Activation 等。我们可以构建任意层数的网络。

代码

输出


步骤 5:构建辅助函数

我们将创建一些辅助函数,这些函数将在模型训练时使用。

  • 采样下一个字符的函数

它将从概率数组中采样一个索引,并将向量转换为 numpy 数组

代码

  • 模型中每个 epoch 后生成文本的函数

此函数将在每个 epoch 执行后生成随机文本

代码

  • 在每个 epoch 损失降低后保存模型的函数。

每当模型执行 epoch 时,都会生成随机文本,并且模型在每个 epoch 后会降低损失,并保存到函数中定义的路径。

代码

  • 降低学习率的函数

此函数有助于在每个 epoch 后降低学习率

代码

步骤 5:模型训练

现在,我们将使用不同的批次和 epoch 来训练模型。这里,我们设置了批次大小为 140epoch 为 40

代码

输出

Text Generation using Gated Recurrent Unit Networks

步骤 6:生成文本

它将生成随机和新的文本

代码

输出

nd kept out of sight
But other girls were never quite
Like this, di-di-di-di'n'd say stame tome trre tars tarl ther stand that there tars in ther stars tame to me st man tars tome trre tars that that on ther stars that on ther stars that the ske stars in ther stars tarl ing and warl that that thatting san that stack in that there tome stass and that the can stars that the trre to ther can tars tome trre tars that the ske stand and that that the skn tars tome trre tome tore tome tore tome
And you say stame tome trre tome that to grin a long tome trre that long tore thars tom.