原文链接:http://tecdat.cn/?p=8448

原文出处:拓端数据部落公众号

文本生成是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 wonne3. That will be ere the set of Sunne1. Where the place?2. Vpon the Heath3. There to meet with Macbeth1. I come, Gray-MalkinAll. 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 = 100for 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库使用深度学习来创建文本生成模型。

拓端tecdat|用于NLP的Python:使用Keras进行深度学习文本生成相关推荐

  1. 拓端tecdat荣获掘金社区入驻新人奖

    2021年7月,由掘金发起了"入驻成长礼"颁奖活动.本次活动邀请到知名开发者.服务机构代表等业界人士. 据了解,掘金社区"新入驻创作者礼"主要对已经积累了一定历 ...

  2. 拓端tecdat荣获2022年度51CTO博主之星

    相信技术,传递价值,这是51CTO每一个技术创作者的动力与信念,2022 年度,拓端tecdat 作为新锐的数据分析咨询公司,在51CTO平台上,不断的输出优质的技术文章,分享前沿创新技术,输出最佳生 ...

  3. 2021-03-28为什么用SCALA语言优势在哪里 Scala适合服务端、大数据、数据挖掘、NLP、图像识别、机器学习、深度学习…等等开发。

    Go适合服务端.桌面应用程序开发. Scala适合服务端.大数据.数据挖掘.NLP.图像识别.机器学习.深度学习-等等开发. Python适合做网络爬虫.自动化运维.快速地实现算法的原型. 但是Pyt ...

  4. 【重磅干货】Python、机器学习、深度学习算法实战和应用必备书籍

    [导读]首先祝大家中秋佳节快乐,乘此良辰美景,今天就给大家发一波福利干货!本文给大家分享机器学习.深度学习算法实战和应用必备的4本"宝藏"书.具体书籍展示如下:(文末提供下载方式! ...

  5. DL框架之Keras:深度学习框架Keras框架的简介、安装(Python库)、相关概念、Keras模型使用、使用方法之详细攻略

    DL框架之Keras:深度学习框架Keras框架的简介.安装(Python库).相关概念.Keras模型使用.使用方法之详细攻略 目录 Keras的简介 1.Keras的特点 2.Keras四大特性 ...

  6. python相关参考文献_深度学习自然语言处理综述,266篇参考文献

    [简介]自然语言处理(NLP)能够帮助智能型机器更好地理解人类的语言,实现基于语言的人机交流.目前随着计算能力的发展和大量语言数据的出现,推动了使用数据驱动方法自动进行语义分析的需求.由于深度学习方法 ...

  7. NLP入门之综述阅读-基于深度学习的自然语言处理研究综述

    NLP入门-综述阅读-[基于深度学习的自然语言处理研究综述] 基于深度学习的自然语言处理研究综述 摘要 0 引言 1 深度学习概述 卷积神经网络 递归神经网络 2 NLP应用研究进展 3 预训练语言模 ...

  8. Keras教程:使用Keras开始深度学习和Python(上)

    概述:包括什么内容呢 用Keras训练第一个简单的神经网络不需要很多代码,但是我们将慢慢开始,逐步进行,确保您理解如何在自己的自定义数据集上训练网络. 我们今天要讨论的步骤包括: 在系统上安装Kera ...

  9. python自动生成标题_使用深度学习自动生成图片标题

    深度学习: 深度学习和机器学习是这个时代最先进的技术.现在将人工智能与人的思想进行比较,在某些领域,人工智能比人类做得更好.每天都有该领域的新研究.这个领域的增长非常快,因为现在我们有足够的计算能力来 ...

  10. py之textgenrnn:Python利用textgenrnn库实现训练文本生成网络

    py之textgenrnn:Python利用textgenrnn库实现训练文本生成网络 目录 输出结果 实现代码 输出结果 实现代码 #textgenrnn:利用textgenrnn实现训练文本生成网 ...

最新文章

  1. java.lang.IncompatibleClassChangeError: Found interface org.apache.poi.util.POILogger, but class was
  2. 用setResult回传intent参数的时候,接收方activity闪退
  3. 数据结构和算法分析:第四章 树
  4. UA MATH566 一个例子:什么是隐状态
  5. mysql 两列互换
  6. Vue封装下拉框组件时,为document绑定原生事件addEventlistener(click“),切换页面之后事件还未被摧毁...
  7. 没了Macbook的英特尔还好吗?比你想象的好
  8. Ubuntu安装显卡驱动详细步骤
  9. c语言编写算术编码,算术编码C语言实现
  10. Android通过百度api地址经纬度获取文字位置信息
  11. Exception | This means that said other beans do not use the final version of the bean. This is often
  12. 公有云迁移,需要考虑的问题
  13. 利用Java和photoShop实现照片拼图
  14. 化工机械基础期末复习题及答案
  15. Sql Server 2008R2 安装教程
  16. Excel数据分析—饼图/圆环图
  17. 求一个数组的全排列(java)
  18. CMU-MOSEI数据集解读
  19. 微信企业支付(一)注意
  20. Mac 本地下载安装Nginx

热门文章

  1. Squid 代理服务器
  2. The Maven Integration requires that Eclipse be running in a JDK……
  3. 【转】ASP.NET Web应用程序写EventLog出错的解决方案
  4. ESC键居然有这样的妙用!!!你知道吗?
  5. 计算点、线、面等元素之间的交点、交线、封闭区域面积和闭合集(待续)
  6. 实验1-利用Debug查看CPU寄存器和内存+利用机器指令和汇编指令编程
  7. 浅析数据链路层的介质访问控制
  8. 使用openssl模拟CA和CA证书的签发
  9. 树莓派安装DLNA实现流媒体服务器
  10. 【No.11 默认实参的匹配】