主要内容

使用深度学习生成文本

这个例子展示了如何训练深度学习长短时记忆(LSTM)网络来生成文本。

为了训练用于文本生成的深度学习网络,训练一个序列到序列的LSTM网络来预测字符序列中的下一个字符。要训练网络预测下一个字符,请指定移动一个时间步长的输入序列作为响应。

要将一组字符序列输入到LSTM网络中,需要将每个训练观测值转换为由向量表示的字符序列 x R D , 在哪里D是词汇表中唯一字符的数量。对于每个向量, x = 1. 如果x对应于与索引的字符在给定的词汇表中,以及 x J = 0 对于 J .

负荷训练数据

从文本文件中提取文本数据sonnets.txt.

文件名=“十四行诗.txt”;textData = fileread(文件名);

十四行诗由两个空格字符缩进,并由两个换行字符分隔。使用以下工具移除压痕:取代并使用分裂. 删除前三个元素的主标题以及出现在每首十四行诗之前的十四行诗标题。

textData=替换(textData,”“,"");的TextData = SPLIT(的TextData,[换行符换行符]);的TextData =的TextData(5:2:结束);

查看前几个观察结果。

文本数据(1:10)
ans =10×1单元阵列{'从最公平的生物,我们的愿望增加,从而↵That美的玫瑰永远不会枯死,↵But作为比较成熟的应时间死亡,↵His招标继承人可能会承担他的记忆:↵But你,承包给你自己明亮的眼睛,↵Feed“ST你的光的火焰与自我实质性的燃料,↵Making一片丰谎言,↵Thy自你的敌人,以你的甜美自己未免太狠:↵Thou艺术现在世界上清新的点缀,只↵And预示着到锦绣阳春,↵Within你自己芽buriest你的内容,↵And招标吝啬鬼mak'st废物吝啬:↵Pity的世界吧,要不然,贪夫,↵To吞噬世界的份,由你和坟墓“。} {“当四十个冬天围攻你的朱颜,↵And挖你的美丽的场深的战壕,↵Thy青春的华服弄到这么盯着现在,↵Will举行小价值的tatter'd杂草:↵Then被要求,在那里所有你的美丽谎言,↵Where是你那少壮年华的宝藏;↵To说,内你自己的深眼窝深陷,↵Were全贪婪的羞耻,和无益的praise.↵How更多的赞誉deserv'd你的美的用途,↵If你couldst答案“这mine↵Shall公平儿童总结我的账,并让我的老迈,”通过继承你↵Proving他的美!↵This将被新做的时候你是老,↵And看到你的血液温暖当你feel'st它冷“。} {“看在你的玻璃,并告诉你的脸是viewest↵Now那张脸应该形成另一个时间;如果现在↵Whose新鲜修理你不renewest,↵Thou就欺骗世界,unbless一些mother.↵For她在哪儿那么公平,其unear'dwomb↵Disdains你牧?↵Or他是谁这么喜欢将坟墓,↵Of他自爱,不要子孙?↵Thou是你母亲的玻璃和她thee↵Calls回来的耕作她的盛年的芳菲四月↵So你通过祢年龄的窗户要看见,↵Despite皱纹你这如果你住金time.↵But,一想起毁灭,↵Die单,与你你的形象模具。“} {'Unthrifty可爱,你为什么spend↵Upon你自己你的美丽的遗产↵Nature的遗赠给了什么,但这话出借,↵And坦率,她借给那些都是免费的:↵Then,美丽的鄙夫,为什么你abuse↵?↵:交给你转交给↵Profitless高利贷者,你为什么use↵So大的和之和,还不能过日子↵For具有单独你自己的流量,你的自我你的自我甜等于欺骗的↵Thou的厚礼那么如何当造化唤你想要离去,↵What接受审计阴间,你还能走吗?↵Thy未使用的美容必须用你tombed,↵Which,用,住个“执行人是。”} {“那些个小时,用温柔的工程也frame↵The注目,每眼岂住,玩↵Will霸到非常same↵And不公平的那些完全这话的Excel;↵For从未停止时间线索夏天on↵为了可怕的冬天,去把它结果;↵Sap霜检查,精力充沛的叶子挺过去了,↵Beauty,把你-雪和裸露每一个地方:↵Then没有夏天的蒸馏左,↵A液体囚犯玻璃幕墙压抑,↵Beauty的美容效果均丧失,↵Nor它,也没有怀念,那是什么:↵But花提炼,虽然他们和冬天,↵Leese但他们的表演; their substance still lives sweet.' } {'Then let not winter's ragged hand deface,↵In thee thy summer, ere thou be distill'd:↵Make sweet some vial; treasure thou some place↵With beauty's treasure ere it be self-kill'd.↵That use is not forbidden usury,↵Which happies those that pay the willing loan;↵That's for thy self to breed another thee,↵Or ten times happier, be it ten for one;↵Ten times thy self were happier than thou art,↵If ten of thine ten times refigur'd thee:↵Then what could death do if thou shouldst depart,↵Leaving thee living in posterity?↵Be not self-will'd, for thou art much too fair↵To be death's conquest and make worms thine heir.' } {'Lo! in the orient when the gracious light↵Lifts up his burning head, each under eye↵Doth homage to his new-appearing sight,↵Serving with looks his sacred majesty;↵And having climb'd the steep-up heavenly hill,↵Resembling strong youth in his middle age,↵Yet mortal looks adore his beauty still,↵Attending on his golden pilgrimage:↵But when from highmost pitch, with weary car,↵Like feeble age, he reeleth from the day,↵The eyes, 'fore duteous, now converted are↵From his low tract, and look another way:↵So thou, thyself outgoing in thy noon:↵Unlook'd, on diest unless thou get a son.' } {'Music to hear, why hear'st thou music sadly?↵Sweets with sweets war not, joy delights in joy:↵Why lov'st thou that which thou receiv'st not gladly,↵Or else receiv'st with pleasure thine annoy?↵If the true concord of well-tuned sounds,↵By unions married, do offend thine ear,↵They do but sweetly chide thee, who confounds↵In singleness the parts that thou shouldst bear.↵Mark how one string, sweet husband to another,↵Strikes each in each by mutual ordering;↵Resembling sire and child and happy mother,↵Who, all in one, one pleasing note do sing:↵Whose speechless song being many, seeming one,↵Sings this to thee: 'Thou single wilt prove none.''} {'Is it for fear to wet a widow's eye,↵That thou consum'st thy self in single life?↵Ah! if thou issueless shalt hap to die,↵The world will wail thee like a makeless wife;↵The world will be thy widow and still weep↵That thou no form of thee hast left behind,↵When every private widow well may keep↵By children's eyes, her husband's shape in mind:↵Look! what an unthrift in the world doth spend↵Shifts but his place, for still the world enjoys it;↵But beauty's waste hath in the world an end,↵And kept unused the user so destroys it.↵No love toward others in that bosom sits↵That on himself such murd'rous shame commits.' } {'For shame! deny that thou bear'st love to any,↵Who for thy self art so unprovident.↵Grant, if thou wilt, thou art belov'd of many,↵But that thou none lov'st is most evident:↵For thou art so possess'd with murderous hate,↵That 'gainst thy self thou stick'st not to conspire,↵Seeking that beauteous roof to ruinate↵Which to repair should be thy chief desire.↵O! change thy thought, that I may change my mind:↵Shall hate be fairer lodg'd than gentle love?↵Be, as thy presence is, gracious and kind,↵Or to thyself at least kind-hearted prove:↵Make thee another self for love of me,↵That beauty still may live in thine or thee.' }

将文本数据转换为序列

将文本数据转换为预测值的向量序列和响应的分类序列。

创建特殊字符来表示“文本开始”,“空白”,“文本结束”和“换行符”。使用特殊字符“\ x0002”(正文开头),“\x00B7”( “·”,中间点),“\x2403”( “␃”,文本的结束),并“\ x00B6”(””段落符号)分别。为了避免含混,你必须选择不会出现在文本中的特殊字符。由于这些字符不训练数据显示,它们可以被用于此目的。

startOfTextCharacter =组成(“\ x0002”);whitespaceCharacter =组成(“\x00B7”);endOfTextCharacter =组成(“\x2403”);newlineCharacter =组成(“\ x00B6”);

对于每一个观察,插入文本字符开始之初并与相应的字符替换空格和换行。

textData = startOfTextCharacter + textData;textData =取代(textData, (”“换行],[whitespaceCharacter newlineCharacter]);

用课文中独特的字符创建一个词汇表。

uniqueCharacters =独特([textData {:}));numUniqueCharacters =元素个数(uniqueCharacters);

对文本数据进行循环,并创建一个表示每个观察的字符的向量序列和一个表示响应的字符的分类序列。要表示每个观察的结束,请包括文本字符的结束。

numDocuments=numel(textData);XTrain=单元格(1,numDocuments);YTrain=单元格(1,数字文档);对于I = 1:numel(的TextData)字符=的TextData {I};sequenceLength = numel(字符);%获取字符的索引。[~,idx]=ismember(字符,唯一字符);%将字符转换为向量。X=零(numiniquecharacters,sequenceLength);对于j=1:序列长度X(idx(j),j)=1;终止%创建带有文本结尾字符的分类响应向量。charactersshift = [cellstr(字符(2:结束)')' endOfTextCharacter];Y =分类(charactersShifted);XTrain{我}= X;YTrain{我}= Y;终止

查看第一个观察到的大小和相应的序列。序列是D——- - - - - -s矩阵,在哪里D是特征数(唯一字符数)和s是序列长度(文本中的字符数)。

textData {1}
ans =从·的····欲望增加,生物¶从而··的·罗斯··美从未·死,¶但是···成熟····时间应该死,¶招标·他···贝尔·他·记忆:继承人¶但你·····你自己的收缩··明亮的眼睛,¶喂花光你···火焰··定情·燃料,¶饥荒使·····丰度所在,¶你的自我···敌人,···你甜蜜自我···cruel:¶现在艺术你·····的·新鲜·点缀,¶和··先驱···华丽·春,¶你··的·巴德·内埋葬你··内容,¶而·温柔·吝啬·花···吝啬鬼:浪费¶遗憾··世界,·或者其他····是贪食,¶世界····吃的,由·····你。”
大小(XTrain {1})
ans =1×262 611

查看相应的响应序列。该序列是一个1-x-s回答的分类向量。

YTrain {1}
ans =1×611分类数组F r o m·F i r e s t·c r e t u r e s w·e·d e s i r e·e n c r e s,¶t h t·h e r e b y·b e u t y ' s·r o s e·m i g h t·n e v e r·d e,¶b u t·s·t h e·r i p e r·s h o u l d b·y·t i m e·d e c e s e,¶h i s·t e n d e r·h e我g h t·r·m b e r·h i s·m e m o r y:¶B u t·h o·c o n t r c t e d·o·t h i n e·o w n·B r i g h t·e y e s,¶F e e d ' s t·t h y·l g h t ' s·F l m e·w i t h·s e l F - s u B s t n t i l·F u e l,¶m k我n g·a·F m n e·w h e r e·B u n d n c e·l i e s,¶t h y y s e l F·t·h·F e阿,·t·t h·s w e e t·s e l f·t o·c r u e l:¶T h o u·T h T·r T·n o w T h·e·w o r l d ' s·f r e s h·o r n a T m e n,¶n d·o n l y·h e r l e d T o·T·h·g d u y·s p r i n g,¶w我T h n·T h n e·o w·b d·b u r i e s T T h·y·c o n T e n T,¶n d·T e n c d e r·h u r l·m k’s T·w s T e·n·n我g g r d i n g:¶P i t y·t h e·w o r l d·o r s e·t·e l h i s·g l u t t o n·b e,¶t o·e·t h e·w o r l d ' s·d u e、b·y·t h e·g r n v e·d·t h e e。␃

建立和培训LSTM网络

定义LSTM体系结构。指定一个序列,以对具有200个隐藏单位的LSTM分类网络进行排序。将训练数据的特征维度(唯一字符数)设置为输入大小,将响应中的类别数设置为完全连接层的输出大小。

inputSize =大小(XTrain {1}, 1);numHiddenUnits = 200;numClasses =元素个数(类别([YTrain {:})));layer = [sequenceInputLayer(inputSize) lstmLayer(numHiddenUnits,'输出outputmode','序列')fullyConnectedLayer(numClasses)softmaxLayer classificationLayer];

指定使用培训选项trainingOptions函数。指定训练周期数为500,初始学习率为0.01。为了防止渐变发生爆炸,设置渐变阈值为2。属性指定在每个epoch中洗牌数据“洗牌”选择“every-epoch”. 要监视培训进度,请设置“情节”选择“培训进度”。若要抑制详细输出,请设置“放牧”错误的.

迷你批量大小选项指定观测过程中的单次迭代的数目。指定小批量大小整除的数据,以确保该函数使用的所有意见进行培训。否则,该函数忽略的意见不完成小批量。将小批生产规模77。

选择= trainingOptions (“亚当”,...“MaxEpochs”,500,...'InitialLearnRate',0.01%,...'GradientThreshold'2,...“MiniBatchSize”, 77,...“洗牌”,“every-epoch”,...“情节”,“培训进度”,...“放牧”,假);

培训网络。

网= trainNetwork (XTrain、YTrain层,选择);

生成新文本

使用生成文本函数,在示例末尾列出,用于使用经过训练的网络生成文本。

这个生成文本函数从文本字符的开头开始逐字符生成文本字符,并使用特殊字符重建文本。该函数使用输出预测分数对每个字符进行采样。当网络预测文本字符结束或生成的文本长度为500个字符时,该函数停止预测。

使用经过训练的网络生成文本。

generateText=generateText(net、uniqueCharacters、startOfTextCharacter、newlineCharacter、whitespaceCharacter、endOfTextCharacter)
生成的文本=“你瞧,你那一群乌合之众躺在哪里,你那最可爱的杠杆却使他们感到骄傲。一颗死亡的心会降临,一个情妇所学的东西会使人的舌头能让人听见,而所有和我在一起的人,我都会幸运地告诉他们;每一个被赋予权利的人,都能以这样的权利,在美好的时光里,在奇迹中,在白天,在黑夜里,在白昼中,在新的时光里,浪费;因为爱玲·瑟斯,我们在这里度过了最美好的时光,因为我的心是莫雷”

文本生成函数

这个生成文本函数从文本字符的开头开始逐字符生成文本字符,并使用特殊字符重建文本。该函数使用输出预测分数对每个字符进行采样。当网络预测文本字符结束或生成的文本长度为500个字符时,该函数停止预测。

函数generateText=generateText(net、uniqueCharacters、startOfTextCharacter、newlineCharacter、whitespaceCharacter、endOfTextCharacter)

通过查找文本字符的索引来创建其开始的向量。

numUniqueCharacters=numel(唯一字符);X=零(numiniquecharacters,1);idx=strfind(uniqueCharacters,startOfTextCharacter);X(idx)=1;

使用用训练LSTM网络生成的字符的文本字符预测和更新房地产数据样本.停止预测当网络预测结束文本的字符或当所生成的文本是长500个字符。这个数据样本函数需要Statistics和Machine Learning Toolbox™。

用于数据,长序列,或大型网络的大的集合,在GPU上的预测是通常更快来计算比所述CPU上的预测。否则,在CPU上的预测通常更快的计算是。对于单时间步长的预测,使用CPU。要使用CPU进行预测,设置“执行环境”选择预测和更新房地产“cpu”.

生成文本="";词汇=字符串(net.Layers(结束). class);最大长度= 500;strlength(generatedText)<最大长度%预测下一个角色的得分。[net,characterScores]=predictAndUpdateState(net,X,“执行环境”,“cpu”);%对下一个字符进行采样。newCharacter=datasample(词汇表,1,“重量”,characterScores);停止预测文本的结尾。如果newCharacter==endOfTextCharacter打破终止%将字符添加到生成的文本中。generatedText = generatedText + newCharacter;%创建下一个输入一个新的载体。X(:)=0;idx=strfind(uniqueCharacters,newCharacter);X(idx)=1;终止

通过将特殊字符替换为相应的空格和换行符来重建生成的文本。

generatedText = replace(generatedText,[newlincharacter whitespaccharacter],[newline . txt],[newline . txt]”“]);终止

另见

|||

相关话题