年過完了,快回來把詩寫完(三)
在前面的訓(xùn)練中,如果你仔細(xì)尋找,會(huì)發(fā)現(xiàn)測(cè)試代碼隱藏在回調(diào)函數(shù)中,但是生成的詩句是隨機(jī)生成的,下面我們就一起來完成隨機(jī)生成詩句、藏頭詩、以及給出首句的方式來測(cè)試生成詩句的效果。
?
首先導(dǎo)入依賴庫,然后加載模型:
import tensorflow.keras as k# import keras as kimport jsonfrom load_data import words_dicimport randomimport numpy as npfrom LoadData import get_data,gen_data,one_hostmodel=k.models.load_model('www.h5')
預(yù)測(cè)函數(shù)
SPRING
接著,我們定義一個(gè)peridct()函數(shù),由于后面需要頻繁地使用到,所以我們把它封裝起來:
# 預(yù)測(cè)函數(shù)def peridct(char):# 數(shù)據(jù)處理xdata = one_host(char, 5552, 1)xdata = xdata.reshape(-1, 6, 5552)p = model.predict(xdata)# 返回預(yù)測(cè)的中文return wordlist[p.argmax()]
藏頭詩
SPRING
然后,我們定義一個(gè)acrostic()函數(shù),用來生成藏頭詩:
# 藏頭詩def acrostic(random_char,char):''':param random_char: 隨機(jī)生成的首句 如:由來稱獨(dú)立:param char: 藏頭的部分:return: 去掉首句后生成的詩。'''random_char+='。' #使首句長度為6# 循環(huán)藏頭的部分for i in char:random_char += i# 依次迭代,每次將一個(gè)藏頭放到句首for j in range(5):x_data=random_char[-6:]cont_index = [wordlist.index(i)if i in wordlist else wordlist.index('z')for i in x_data]next_=peridct([cont_index])random_char+=next_return random_char[6:]
隨機(jī)生成詩句
SPRING
# 隨機(jī)生成def random_gan(random_char,model,key):random_char+=','for i in range(18):x_data=random_char[-6:]next_=peridct(model,x_data,key)random_char+=next_return random_char
給出首句生成詩句
SPRING
# 給第一句def give_first(first_char):first_char+=','for i in range(18):x_data = first_char[-6:]cont_index = [wordlist.index(i) if i in wordlist else wordlist.index('z') for i in x_data]# print(x_data)next_ = peridct([cont_index])first_char += next_return first_char
最后,在main函數(shù)中寫入如下代碼,就可以生成三種不同的詩句了:
if __name__ == '__main__':cont,wordlist=get_data()ranint=random.randint(1,20000)words=cont[ranint].split(',')[0]char=acrostic(words,'你好再見')print(char)print('\n-----------------------------')char = random_gan(words)print(char)print('\n-----------------------------')char = give_first('由來稱獨(dú)立')print(char)
生成的結(jié)果如下:

本章中,我們使用了RNN進(jìn)行詩詞的生成,涉及的技術(shù)包括:文本處理,字典生成,詞向量生成等。當(dāng)然,同學(xué)們有興趣的話,可以將我們的RNN換成LSTM或者GRU等算法,看看最終生成的結(jié)果是否更加有意境。
評(píng)論
圖片
表情
