主要内容

使用深度学习生成文本

此示例显示如何培训深度学习长期内存(LSTM)网络以生成文本。

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

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

负载培训数据

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

filename =.“sonnets.txt”;textdata = fileread(filename);

SONNET由两个空格字符缩进,并被两个换行符分隔。使用缩进使用代替并将文本分成单独的十四圈使用分裂。从每个十四行列网之前的前三个元素和十四行标题中删除主标题。

textdata = replace(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)分别。为防止歧义,您必须选择未在文本中出现的特殊字符。因为这些字符不会出现在训练数据中,因此它们可以用于此目的。

startoftextacharacter = compose(“\ x0002”);WhitespaceCharacter = Compose(“\ x00b7”);EndoftextCharacter = Compose(“\ x2403”);newlineCharacter = compose(“\ x00b6”);

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

textdata = startoftextacharacter + textdata;textdata = replace(textdata,[纽诺],[WhiteSpaceCharacter NewLiceCharacter]);

在文本中创建唯一字符的词汇。

uniquecharacters =唯一([textdata {:}]);numuniquecharacters = numel(uniquecharacters);

循环在文本数据上,并创建一个序列,表示每个观察的字符和响应的字符的分类序列。要表示每个观察的末尾,包括文本字符的结尾。

numdocuments = numel(textdata);XTrain = Cell(1,NumFocuments);YTrain = Cell(1,NumFocuments);为了i = 1:numel(textdata)字符= textdata {i};sequencelength = numel(字符);%获得字符指数。[〜,idx] = ismember(字符,uniqueRegracters);%将字符转换为向量。x =零(NumUnupteCharacters,Sequencelencth);为了j = 1:sequencelength x(idx(j),j)= 1;结尾%创建与文本字符结尾的分类响应的向量。字符次= [CellStr(字符(2:结束)')'EndoftextCharacter];y =分类(Charactersshifted);xtrain {i} = x;ytrain {i} = y;结尾

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

TextData {1}
Ans ='来自最公平的生物·我们·愿望·增加,¶这直·美丽的·玫瑰·可能·永远不会·死亡,¶然后··波纹··马达····时间·减少,√HIS·招标·继承人·熊·熊·他·记忆:¶然后·你,·契约·············眼睛,�feed'st·thy·光的火焰··自我大量·燃料,¶制作·A·饥荒·大量·谎言·谎言·谎言,¶thy·自我·你·敌人,·thy·thy·甜蜜·自我·to·残忍:¶··艺术·现在·世界的··新鲜·装饰那¶And·only·herald·to·the·gaudy·spring,¶Within·thine·own·bud·buriest·thy·content,¶And·tender·churl·mak'st·waste·in·niggarding:¶Pity·the·world,·or·else·this·glutton·be,¶To·eat·the·world's·due,·by·the·grave·and·thee.'
尺寸(xtrain {1})
ans =.1×262 611.

查看相应的响应序列。序列是一个1-by-S.响应的分类矢量。

Ytrain {1}
ans =.1×611分类阵列F r o m · f a i r e s t · c r e a t u r e s · w e · d e s i r e · i n c r e a s e , ¶ T h a t · t h e r e b y · b e a u t y ' s · r o s e · m i g h t · n e v e r · d i e , ¶ B u t · a 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 a s e , ¶ H i s · t e n d e r · h e i r · m i g h t · b e a r · h i s · m e m o r y : ¶ B u t · t h o u , · c o n t r a c t e d · t 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 i g h t ' s · f l a m e · w i t h · s e l f - s u b s t a n t i a l · f u e l , ¶ M a k i n g · a · f a m i n e · w h e r e · a b u n d a n c e · l i e s , ¶ T h y · s e l f · t h y · f o e , · t o · t h y · s w e e t · s e l f · t o o · c r u e l : ¶ T h o u · t h a t · a r t · n o w · t h e · w o r l d ' s · f r e s h · o r n a m e n t , ¶ A n d · o n l y · h e r a l d · t o · t h e · g a u d y · s p r i n g , ¶ W i t h i n · t h i n e · o w n · b u d · b u r i e s t · t h y · c o n t e n t , ¶ A n d · t e n d e r · c h u r l · m a k ' s t · w a s t e · i n · n i g g a r d i n g : ¶ P i t y · t h e · w o r l d , · o r · e l s e · t h i s · g l u t t o n · b e , ¶ T o · e a t · t h e · w o r l d ' s · d u e , · b y · t h e · g r a v e · a n d · t h e e . ␃

创建和训练LSTM网络

定义LSTM架构。指定具有200个隐藏单元的序列到序列LSTM分类网络。将培训数据的特征维(唯一字符数)设置为输入大小,以及响应中的类别数量作为完全连接图层的输出大小。

InputSize = Size(XTrain {1},1);numhidendunits = 200;numclasses = numel(类别([ytrain {:}]));图层= [sequenceInputlayer(inputsize)lstmlayer(numhidentunits,'OutputMode''顺序')全连接列(numclasses)softmaxlayer分类层];

使用使用的培训选项培训选项功能。指定培训次数为500,初始学习率为0.01。为防止渐变爆炸,将渐变阈值设置为2.指定以通过设置设置每个时代的数据'洗牌'选择'每个时代'。要监控培训进度,请设置'plots'选择'培训 - 进步'。要抑制详细输出,请设置'verbose'错误的

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

选项=培训选项('亚当'......'maxepochs',500,......'italllearnrate',0.01,......'gradientthreshold'2,......'minibatchsize',77,......'洗牌''每个时代'......'plots''培训 - 进步'......'verbose',错误的);

训练网络。

net = trainnetwork(xtrain,ytrain,图层,选项);

生成新文本

使用generatext.函数,在示例的末尾列出,用于使用培训的网络生成文本。

generatext.函数按字符生成文本字符,从文本字符的开始开始,并使用特殊字符重建文本。该功能使用输出预测分数对每个字符进行采样。函数停止预测当网络预测文本末端字符或生成的文本长时间为500个字符时。

使用培训的网络生成文本。

生成ext = generateText(net,unqueharacters,startoftextacharacter,newlineCharacter,whitespaceCharacter,Endoftextcharacter)
生成的图案=“看,那个丑陋的toor男人的百胜数,在你最甜蜜的地方感到愉快,但杠杆谎言。一个成交的死亡之一,它给予了女主人,一个人听到的男人们的舌头以及他们所有与我同在的人,我财富到简要介绍一下;并且每个卑微的屁股都可以通过Genilir'd Lime Thau小时,而令人讨厌的是,令人惊叹的时间,和那天你的夜晚是新的,然后是新的;对于Ailling Thuse借来的静脉福明在这里花了,因为我的心越来越“

文本生成功能

generatext.函数按字符生成文本字符,从文本字符的开始开始,并使用特殊字符重建文本。该功能使用输出预测分数对每个字符进行采样。函数停止预测当网络预测文本末端字符或生成的文本长时间为500个字符时。

功能生成ext = generateText(net,unqueharacters,startoftextacharacter,newlineCharacter,whitespaceCharacter,Endoftextcharacter)

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

numuniquecharacters = numel(uniquecharacters);x =零(NumUniqueCharacters,1);idx = strfind(uniqueRegracters,startoftextacharacter);x(IDX)= 1;

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

对于大量数据,长序列或大型网络,GPU的预测通常比CPU上的预测更快地计算成计算。否则,对CPU的预测通常更快以计算。有关单时间步骤预测,请使用CPU。要使用CPU进行预测,请设置'executionenvironment'选择predictandanddatestate.'中央处理器'

生成图=;词汇=字符串(Net.Layers(END).classes);maxlength = 500;尽管strlength(生成文本)%预测下一个字符分数。[net,charactercores] = predictandanddattestate(net,x,'executionenvironment''中央处理器');%样本下一个字符。newcharacter = datasample(词汇,1,'重量',字符);%停止在文本结束时预测。如果newcharacter == EXTOFTEXTRACTR.休息结尾%将字符添加到生成的文本。生成ext =生成的文本+ newcharacter;%为下一个输入创建一个新的向量。x(:) = 0;idx = strfind(无字符,newcharacters);x(IDX)= 1;结尾

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

生成的文本= replace(生成的文本,[newlineCharacter whitespaceCharacter],[换行符]);结尾

也可以看看

|||

相关话题