用于NLP的Python:使用Keras进行深度学习文本生成

本文涉及的产品
NLP 自学习平台,3个模型定制额度 1个月
NLP自然语言处理_基础版,每接口每天50万次
NLP自然语言处理_高级版,每接口累计50万次
简介: 用于NLP的Python:使用Keras进行深度学习文本生成

文本生成是NLP的最新应用之一。深度学习技术已用于各种文本生成任务,例如写作诗歌,生成电影脚本甚至创作音乐。但是,在本文中,我们将看到一个非常简单的文本生成示例,其中给定输入的单词字符串,我们将预测下一个单词。我们将使用莎士比亚著名小说《麦克白》的原始文本,并根据给定的一系列输入单词来预测下一个单词。

完成本文之后,您将能够使用所选的数据集执行文本生成

导入库和数据集

第一步是导入执行本文中的脚本所需的库以及数据集。以下代码导入所需的库:

import numpy as np
from keras.models import Sequential, load_model
from keras.layers import Dense, Embedding, LSTM, Dropout

下一步是下载数据集。我们将使用Python的NLTK库下载数据集。

download('gutenberg')

您应该看到以下输出:

\['austen-emma.txt', 'austen-persuasion.txt', 'austen-sense.txt', 'bible-kjv.txt', 'blake-poems.txt', 'bryant-stories.txt', 'burgess-busterbrown.txt', 'carroll-alice.txt', 'chesterton-ball.txt', 'chesterton-brown.txt', 'chesterton-thursday.txt', 'edgeworth-parents.txt', 'melville-moby_dick.txt', 'milton-paradise.txt', 'shakespeare-caesar.txt', 'shakespeare-hamlet.txt', 'shakespeare-macbeth.txt', 'whitman-leaves.txt'\]

该文件包含小说“ Macbeth”的原始文本。要从此文件读取文本,可以使用类中的raw方法:

macbeth_text = corpus.gutenberg.raw('shakespeare-macbeth.txt')

让我们从数据集中输出前500个字符:

print(macbeth_text\[:500\])

这是输出:

Actus Primus. Scoena Prima.
Thunder and Lightning. Enter three Witches.
  1. When shall we three meet againe?
In Thunder, Lightning, or in Raine?
  2. When the Hurley-burley's done,
When the Battaile's lost, and wonne
   3. That will be ere the set of Sunne
   1. Where the place?
  2. Vpon the Heath
   3. There to meet with Macbeth
   1. I come, Gray-Malkin
   All. Padock calls anon: faire is foule, and foule is faire,
Houer through

您会看到文本包含许多特殊字符和数字。下一步是清理数据集。

数据预处理

要删除标点符号和特殊字符,我们将定义一个名为的函数preprocess_text()

def preprocess_text(sen):
    # 删除标点符号和数字
    sentence = re.sub('\[^a-zA-Z\]', ' ', sen)
...
    return sentence.lower()

preprocess_text函数接受文本字符串作为参数,并以小写形式返回清理后的文本字符串。

现在让我们清理文本,然后再次输出前500个字符:

macbeth\_text = preprocess\_text(macbeth_text)
macbeth_text\[:500\]

这是输出:

the tragedie of macbeth by william shakespeare actus primus scoena prima thunder and lightning enter three witches when shall we three meet againe in thunder lightning or in raine when the hurley burley done when the battaile lost and wonne that will be ere the set of sunne where the place vpon the heath there to meet with macbeth come gray malkin all padock calls anon faire is foule and foule is faire houer through the fogge and filthie ayre exeunt scena secunda alarum within enter king malcom

将单词转换为数字

深度学习模型基于统计算法。因此,为了使用深度学习模型,我们需要将单词转换为数字。

在本文中,我们将使用一种非常简单的方法,将单词转换为单个整数。在将单词转换为整数之前,我们需要将文本标记为单个单词

以下脚本标记我们数据集中的文本,然后输出数据集中的单词总数以及数据集中的唯一单词总数:

from nltk.tokenize import word_tokenize
...
print('Total Words: %d' % n_words)
print('Unique Words: %d' % unique_words)

输出这样:

Total Words: 17250
Unique Words: 3436

我们的文字总共有17250个单词,其中3436个单词是唯一的。要将标记化的单词转换为数字,可以使用模块中的keras.preprocessing.text。您需要调用该fit_on_texts方法并将其传递给单词列表。将创建一个字典,其中的键将代表单词,而整数将代表字典的相应值。

看下面的脚本:

from keras.preprocessing.text import Tokenizer
...

要访问包含单词及其相应索引的字典,word_index可以使用tokenizer对象的属性:

vocab\_size = len(tokenizer.word\_index) + 1
word\_2\_index = tokenizer.word_index

如果您检查字典的长度,它将包含3436个单词,这是我们数据集中唯一单词的总数。

现在让我们从字典中输出第500个唯一单词及其整数值。

print(macbeth\_text\_words\[500\])
print(word\_2\_index\[macbeth\_text\_words\[500\]\])

这是输出:

comparisons
1456

修改数据形状

LSTM接受3维格式的数据(样本数,时间步数,每个时间步的特征)。由于输出将是单个单词,因此输出的形状将是二维的(样本数,语料库中唯一词的数量)。

以下脚本修改了输入序列和相应输出的形状。

input_sequence = \[\]
output_words = \[\]
input\_seq\_length = 100
for i in range(0, n\_words - input\_seq_length , 1):
    in\_seq = macbeth\_text\_words\[i:i + input\_seq_length\]
...

在上面的脚本中,我们声明两个空列表input_sequenceoutput_words。将input_seq_length被设置为100,这意味着我们的输入序列将包括100个字。接下来,我们执行一个循环,在第一次迭代中,将文本中前100个单词的整数值附加到input_sequence列表中。第101个单词将追加到output_words列表中。在第二次迭代过程中,从文本中的第二个单词开始到第101个单词结束的单词序列存储在input_sequence列表中,第102个单词存储在output_words数组中,依此类推。由于数据集中共有17250个单词(比单词总数少100个),因此将总共生成17150个输入序列。

现在让我们输出input_sequence列表中第一个序列的值:

print(input_sequence\[0\])

输出:

\[1, 869, 4, 40, 60, 1358, 1359, 408, 1360, 1361, 409, 265, 2, 870, 31, 190, 291, 76, 36, 30, 190, 327, 128, 8, 265, 870, 83, 8, 1362, 76, 1, 1363, 1364, 86, 76, 1, 1365, 354, 2, 871, 5, 34, 14, 168, 1, 292, 4, 649, 77, 1, 220, 41, 1, 872, 53, 3, 327, 12, 40, 52, 1366, 1367, 25, 1368, 873, 328, 355, 9, 410, 2, 410, 9, 355, 1369, 356, 1, 1370, 2, 874, 169, 103, 127, 411, 357, 149, 31, 51, 1371, 329, 107, 12, 358, 412, 875, 1372, 51, 20, 170, 92, 9\]

让我们通过将序列中的整数除以最大整数值来归一化输入序列。以下脚本还将输出转换为二维格式。

以下脚本输出输入和相应输出的形状。

print("X shape:", X.shape)
print("y shape:", y.shape)

输出:

X shape: (17150, 100, 1)
y shape: (17150, 3437)

训练模型

下一步是训练我们的模型。关于应使用多少层和神经元来训练模型,没有硬性规定。

我们将创建三个LSTM层,每个层具有800个神经元。最终将添加具有1个神经元的密集层,来预测下一个单词的索引,如下所示:

...
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='adam')

由于输出单词可以是3436个唯一单词之一,因此我们的问题是多类分类问题,因此使用categorical_crossentropy损失函数。如果是二进制分类,binary_crossentropy则使用该函数。执行上面的脚本,可以看到模型摘要:

Model: "sequential_1"
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
Layer (type)                 Output Shape              Param #
=================================================================
lstm_1 (LSTM)                (None, 100, 800)          2566400
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
lstm_2 (LSTM)                (None, 100, 800)          5123200
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
lstm_3 (LSTM)                (None, 800)               5123200
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
dense_1 (Dense)              (None, 3437)              2753037
=================================================================
Total params: 15,565,837
Trainable params: 15,565,837
Non-trainable params: 0

要训练模型,我们可以简单地使用该fit()方法。

model.fit(X, y, batch_size=64, epochs=10, verbose=1)

预测

为了进行预测,我们将从input_sequence列表中随机选择一个序列,将其转换为3维形状,然后将其传递给predict()训练模型的方法。然后将索引值传递到index_2_word字典,在字典中将单词index用作键。该index_2_word字典将返回属于被作为重点字典传入的索引词。

以下脚本随机选择一个整数序列,然后输出相应的单词序列:

...
print(' '.join(word_sequence))

对于本文中的脚本,以下顺序是随机选择的:

amen when they did say god blesse vs lady consider it not so deepely mac but wherefore could not pronounce amen had most need of blessing and amen stuck in my throat lady these deeds must not be thought after these wayes so it will make vs mad macb me thought heard voyce cry sleep no more macbeth does murther sleepe the innocent sleepe sleepe that knits vp the rauel sleeue of care the death of each dayes life sore labors bath balme of hurt mindes great natures second course chiefe nourisher in life feast lady what doe you meane

接下来,我们将按照上述单词顺序输出接下来的100个单词:

for i in range(100):
    int\_sample = np.reshape(random\_seq, (1, len(random_seq), 1))
    int\_sample = int\_sample / float(vocab_size)
...

word_sequence现在,变量包含我们输入的单词序列以及接下来的100个预测单词。该word_sequence变量包含列表形式的单词序列。我们可以简单地将列表中的单词连接起来获得最终的输出序列,如下所示:

final_output = ""
for word in word_sequence:
...
print(final_output)

这是最终输出:

amen when they did say god blesse vs lady consider it not so deepely mac but wherefore could not pronounce amen had most need of blessing and amen stuck in my throat lady these deeds must not be thought after these wayes so it will make vs mad macb me thought heard voyce cry sleep no more macbeth does murther sleepe the innocent sleepe sleepe that knits vp the rauel sleeue of care the death of each dayes life sore labors bath balme of hurt mindes great natures second course chiefe nourisher in life feast lady what doe you meane and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and

结论

在本文中,我们看到了如何通过Python的Keras库使用深度学习来创建文本生成模型。

相关文章
|
5月前
|
数据采集 自然语言处理 分布式计算
大数据岗位技能需求挖掘:Python爬虫与NLP技术结合
大数据岗位技能需求挖掘:Python爬虫与NLP技术结合
|
7月前
|
数据采集 机器学习/深度学习 自然语言处理
NLP助力非结构化文本抽取:实体关系提取实战
本文介绍了一套基于微博热帖的中文非结构化文本分析系统,通过爬虫代理采集数据,结合NLP技术实现实体识别、关系抽取及情感分析。核心技术包括爬虫模块、请求配置、页面采集和中文NLP处理,最终将数据结构化并保存为CSV文件或生成图谱。代码示例从基础正则规则到高级深度学习模型(如BERT-BiLSTM-CRF)逐步演进,适合初学者与进阶用户调试与扩展,展现了中文NLP在实际场景中的应用价值。
514 3
NLP助力非结构化文本抽取:实体关系提取实战
|
7月前
|
存储 机器学习/深度学习 人工智能
多模态RAG实战指南:完整Python代码实现AI同时理解图片、表格和文本
本文探讨了多模态RAG系统的最优实现方案,通过模态特定处理与后期融合技术,在性能、准确性和复杂度间达成平衡。系统包含文档分割、内容提取、HTML转换、语义分块及向量化存储五大模块,有效保留结构和关系信息。相比传统方法,该方案显著提升了复杂查询的检索精度(+23%),并支持灵活升级。文章还介绍了查询处理机制与优势对比,为构建高效多模态RAG系统提供了实践指导。
1849 0
多模态RAG实战指南:完整Python代码实现AI同时理解图片、表格和文本
|
10月前
|
机器学习/深度学习 PyTorch TensorFlow
深度学习工具和框架详细指南:PyTorch、TensorFlow、Keras
在深度学习的世界中,PyTorch、TensorFlow和Keras是最受欢迎的工具和框架,它们为研究者和开发者提供了强大且易于使用的接口。在本文中,我们将深入探索这三个框架,涵盖如何用它们实现经典深度学习模型,并通过代码实例详细讲解这些工具的使用方法。
|
机器学习/深度学习 自然语言处理 API
如何使用阿里云的语音合成服务(TTS)将文本转换为语音?本文详细介绍了从注册账号、获取密钥到编写Python代码调用TTS服务的全过程
如何使用阿里云的语音合成服务(TTS)将文本转换为语音?本文详细介绍了从注册账号、获取密钥到编写Python代码调用TTS服务的全过程。通过简单的代码示例,展示如何将文本转换为自然流畅的语音,适用于有声阅读、智能客服等场景。
4286 3
|
机器学习/深度学习 自然语言处理 知识图谱
GraphRAG在自然语言处理中的应用:从问答系统到文本生成
【10月更文挑战第28天】作为一名自然语言处理(NLP)和图神经网络(GNN)的研究者,我一直在探索如何将GraphRAG(Graph Retrieval-Augmented Generation)模型应用于各种NLP任务。GraphRAG结合了图检索和序列生成技术,能够有效地处理复杂的语言理解和生成任务。本文将从个人角度出发,探讨GraphRAG在构建问答系统、文本摘要、情感分析和自动文本生成等任务中的具体方法和案例研究。
523 5
|
自然语言处理 Python
如何使用自然语言处理库`nltk`进行文本的基本处理
这段Python代码展示了如何使用`nltk`库进行文本的基本处理,包括分词和词频统计。首先需要安装`nltk`库,然后通过`word_tokenize`方法将文本拆分为单词,并使用`FreqDist`类统计每个单词的出现频率。运行代码后,会输出每个词的出现次数,帮助理解文本的结构和常用词。
322 1
|
人工智能 自然语言处理 语音技术
利用Python进行自然语言处理(NLP)
利用Python进行自然语言处理(NLP)
194 1
|
人工智能 自然语言处理 语音技术
利用Python进行自然语言处理(NLP)
利用Python进行自然语言处理(NLP)
324 3

热门文章

最新文章

推荐镜像

更多