主要内容

使用深度学习生成文本

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

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

为了将一个字符序列输入到LSTM网络中,将每个训练观察结果转换为由向量表示的字符序列 x R D , 在哪里D是词汇表中唯一字符的数量。对于每一个向量, x 1 如果x对应于索引的字符在给定的词汇表中,和 x j 0 j

负荷训练数据

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

文件名=“sonnets.txt”;textData = fileread(文件名);

十四行诗由两个空格字符缩进,并由两个换行字符分隔。删除缩进使用取代然后用十四行诗把文本分开分裂.从每个十四行列网之前的前三个元素和十四行标题中删除主标题。

textData =取代(textData,”“"");textdata = split(textdata,[newline newline]);TextData = TextData(5:2:结束);

看看最初的几个观察结果。

TextData(1:10)
ans =10×1单元阵列{“来自最公平的生物我们渴望增加,↵这直玫瑰可能永远不会死,↵在涟漪应该按时间去死,↵his温柔的继承人可能会忍受他的记忆:↵你,签约到自己的明亮的眼睛,�feed“你的光的火焰与自我大量的燃料,↵在丰富的地方制造着饥荒,↵thyself thy foe,对你的甜蜜的自我太残忍了:↵你现在是世界上新的装饰品,↵只有先驱到华丽的春天,↵Withinth致密的你的内容,↵嫩的Churl Mak'st废物在琐事中:↵是世界,否则这个贪吃,↵↵grave坟墓,由坟墓和坟墓。} {'当四十冬天围攻你的眉头时,↵在你们美丽的领域的深沟挖掘,↵你现在所凝视的骄傲的衣服如此凝视着,↵会是一个杂草的小杂志:↵然后在哪里被问到,在哪里所有你的美丽谎言,你的疯狂日的所有宝藏;↵留言,在你自己深沉的沉没的眼中,↵↵eating↵↵羞耻,百饱了一致好评。↵越多,越来越多的赞美你的美女,↵如果你可以回答'这个公平的孩子的雷霆的孩子,我的伯爵和我的古老借口,'↵通过继承的美丽来!↵这是新的,当你艺术老,↵看到你的血液温暖当你感到寒冷时。} {'看着你的玻璃,告诉脸,你愿意地看着脸部应该形成另一个;↵当你现在没有早新的时候,↵你砍掉了世界,不忽视一些母亲.↵她在哪里如此公平,其发出的obb↵disdains耕种你的牧草?谁是他如此喜欢,这将是坟墓,他的自爱停止后代?↵艺术你的玻璃杯和她在伊恩广场回来她的素质是可爱的4月;↵你通过Windows的Thine Shalt看到,↵皱纹这个你的黄金时间。请记住,不要成为,↵die单身和留下图像与你一起死亡。'} {'不可忽视的可爱,为什么要努力花费你的自我你的遗产?↵nature的贝斯特没有给出任何东西,而是Doth Leend,↵坦克她借给那些有空的人:↵然后↵bea bea n n,忠实的巨大的吉尔斯给了你们给予?↵谬论的用户,为什么要使用这么大的总和,但才能没有生活?↵与你的自我交通,↵你的自我你的甜蜜自我dost欺骗:♥那么当自然叫你的时候,你是如何消失的,↵你是可接受的审计迦兜吗?你会离开吗?↵ththy未使用的美丽必须是玉米,↵为什么使用,生命的刽子手。“} {'那些小时,温柔的工作做了框架↵↵g g居住的凝视,↵会把暴君发挥到同样的地方,这相当不公平,这是一个相当的excel;↵从不休息的时间导致夏天丑陋的冬天,在那里混淆了他;����������叶子已经消失了,�美丽的叶子,每一个下雪和痛苦的地方:↵然后不是夏天的蒸馏留下,↵液体囚犯在玻璃墙上浮出水面,↵美容的美丽的效果是突然忘记了,↵↵,也没有纪念它是什么:↵“鲜花蒸馏的人,尽管他们与冬季相遇,但他们的展示; 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”(““,pilcrow)分别。为防止歧义,您必须选择未在文本中出现的特殊字符。因为这些字符不会出现在训练数据中,因此它们可以用于此目的。

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

对于每个观察,在开始时插入文本字符的开始,并用相应的字符替换空格和换行符。

textData = starttoftextcharacter + textData;textData =取代(textData, (”“纽诺],[WhiteSpaceCharacter NewLiceCharacter]);

创建一个词汇的独特字符在文本。

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

循环遍历文本数据并创建表示每个观察的字符的向量序列和用于响应的字符分类序列。要表示每个观察的结束,请包含文本结束字符。

numDocuments =元素个数(textData);XTrain =细胞(1、numDocuments);YTrain =细胞(1、numDocuments);i = 1:numel(textdata)字符= textdata {i};sequencelength = numel(字符);%获取字符索引。[~, idx] = ismember(字符,uniqueCharacters);%将字符转换为向量。X = 0 (numUniqueCharacters sequenceLength);X(idx(j),j) = 1;结束%创建带有文本结束字符的类别响应向量。charactersmoved = [cellstr(characters(2:end)')' endftextcharacter];Y =分类(charactersShifted);XTrain{我}= X;YTrain{我}= Y;结束

查看第一个观察到的大小和相应的序列。序列是D——- - - - - -年代矩阵,其中D是功能的数量(唯一字符的数量)和年代是序列长度(文本中的字符数)。

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

查看对应的响应顺序。这个序列是1-年代反应的分类向量。

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 o·t h y·s w 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 {:})));lstmLayer(numHiddenUnits, numHiddenUnits)'OutputMode''顺序') fullconnectedlayer (numClasses) softmaxLayer classiationlayer];

使用使用的培训选项trainingOptions函数。指定训练周期数为500,初始学习速率为0.01。为了防止梯度爆炸,设置梯度阈值为2。属性指定每个epoch洗牌数据'洗牌'选择“every-epoch”.要监控培训进度,请设置“阴谋”选择“训练进步”.要抑制详细输出,请设置'verbose'错误的

mini-batch size选项指定在单个迭代中处理的观察次数。指定均匀批次尺寸,均匀地划分数据,以确保该功能使用所有观察培训。否则,该函数忽略了不完成迷你批次的观察结果。将迷你批量尺寸设置为77。

选择= trainingOptions (“亚当”...“MaxEpochs”, 500,...'italllearnrate',0.01,...'gradientthreshold'2,...“MiniBatchSize”, 77,...'洗牌'“every-epoch”...“阴谋”“训练进步”...'verbose',错误的);

培训网络。

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

生成新的文本

使用generateText函数,该函数列出在示例的最后,用于使用经过训练的网络生成文本。

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

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

generatedText = generateText(网,uniqueCharacters, startOfTextCharacter、newlineCharacter whitespaceCharacter, endOfTextCharacter)
“看,你的那些痴情的男人,在你最甜美的地方,却躺着一根不舒服的利索。死神做了一笔交易,让人心如水水;她能学到的东西,能让人听得见;每一幅画都能以这种正确的野心,把时间花在花上,把奇思妙想抛在后头,日日夜夜,把青春消磨;既然我的心已憔悴,

文本生成函数

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

函数generatedText = generateText(网,uniqueCharacters, startOfTextCharacter、newlineCharacter whitespaceCharacter, endOfTextCharacter)

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

numUniqueCharacters =元素个数(uniqueCharacters);x =零(NumUniqueCharacters,1);idx = strfind(uniqueRegracters,startoftextacharacter);X (idx) = 1;

使用训练的LSTM网络使用训练的LSTM网络生成文本字符predictAndUpdateStatedatasample.停止预测网络当网络预测到文本末端字符或当生成的文本长时间为500个字符时。的datasample功能需要统计和机器学习工具箱™。

对于大量数据,长序列或大型网络,GPU的预测通常比CPU上的预测更快地计算成计算。否则,对CPU的预测通常更快以计算。有关单时间步骤预测,请使用CPU。要使用CPU进行预测,请设置“ExecutionEnvironment”选择predictAndUpdateState“cpu”

generatedText ="";词汇=字符串(net.Layers(结束). class);最大长度= 500;strlength(生成文本)预测下一个角色的得分。[净,characterScores] = predictAndUpdateState(净,X,“ExecutionEnvironment”“cpu”);%样本下一个字符。newCharacter = datasample(词汇,1,“重量”,字符);在文本结束时停止预测。如果newCharacter = = endOfTextCharacter打破结束%将字符添加到生成的文本中。生成ext =生成的文本+ newcharacter;%为下一个输入创建一个新的向量。X (,) = 0;idx = strfind (uniqueCharacters newCharacter);X (idx) = 1;结束

用相应的空格和换行符替换特殊字符,重新构造生成的文本。

generatedText = replace(generatedText,[newlineCharacter whitespaceCharacter],[newline . txt])”“]);结束

另请参阅

|||

相关话题