基于循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的古詩生成器,具體內(nèi)容如下
之前在手機(jī)百度上看到有個(gè)“為你寫詩”功能,能夠隨機(jī)生成古詩,當(dāng)時(shí)感覺很酷炫= =
在學(xué)習(xí)了深度學(xué)習(xí)后,了解了一下原理,打算自己做個(gè)實(shí)現(xiàn)練練手,于是,就有了這個(gè)項(xiàng)目。文中如有瑕疵紕漏之處,還請(qǐng)路過的諸位大佬不吝賜教,萬分感謝!
使用循環(huán)神經(jīng)網(wǎng)絡(luò)實(shí)現(xiàn)的古詩生成器,能夠完成古體詩的自動(dòng)生成。我簡單地訓(xùn)練了一下,格式是對(duì)上了,至于意境么。。。emmm,呵呵
舉一下模型測(cè)試結(jié)果例子:
1.生成古體詩
示例1:
樹陰飛盡水三依,謾自為能厚景奇。
莫怪仙舟欲西望,楚人今此惜春風(fēng)。
示例2:
巖外前苗點(diǎn)有泉,紫崖煙靄碧芊芊。
似僧月明秋更好,一蹤顏事欲猶傷?
2.生成藏頭詩(以“神策”為例)
示例1:
神照隆祭測(cè)馨塵,策紫瓏氳羽團(tuán)娟。
示例2:
神輦鶯滿花臺(tái)潭,策窮漸見仙君地。
下面記錄項(xiàng)目實(shí)現(xiàn)過程(由于都是文本處理方面,跟前一個(gè)項(xiàng)目存在很多類似的內(nèi)容,對(duì)于這部分內(nèi)容,我就只簡單提一下,不展開了,新的東西再具體說):
1.數(shù)據(jù)預(yù)處理
數(shù)據(jù)集使用四萬首的唐詩訓(xùn)練集,可以點(diǎn)擊這里進(jìn)行下載。
數(shù)據(jù)預(yù)處理的過程與前一個(gè)項(xiàng)目TensorFlow練手項(xiàng)目一:使用循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)實(shí)現(xiàn)影評(píng)情感分類大同小異,可以參考前一個(gè)項(xiàng)目,這里就不多說了,直接上代碼。
# -*- coding: utf-8 -*-# @Time : 18-3-13 上午11:04# @Author : AaronJny# @Email : Aaron__7@163.comimport sysreload(sys)sys.setdefaultencoding('utf8')import collectionsORIGIN_DATA = 'origin_data/poetry.txt' # 源數(shù)據(jù)路徑OUTPUT_DATA = 'processed_data/poetry.txt' # 輸出向量路徑VOCAB_DATA = 'vocab/poetry.vocab'def word_to_id(word, id_dict): if word in id_dict: return id_dict[word] else: return id_dict['<unknow>']poetry_list = [] # 存放唐詩的數(shù)組# 從文件中讀取唐詩with open(ORIGIN_DATA, 'r') as f: f_lines = f.readlines() print '唐詩總數(shù) : {}'.format(len(f_lines)) # 逐行進(jìn)行處理 for line in f_lines: # 去除前后空白符,轉(zhuǎn)碼 strip_line = line.strip().decode('utf8') try: # 將唐詩分為標(biāo)題和內(nèi)容 title, content = strip_line.split(':') except: # 出現(xiàn)多個(gè)':'的將被舍棄 continue # 去除內(nèi)容中的空格 content = content.strip().replace(' ', '') # 舍棄含有非法字符的唐詩 if '(' in content or '(' in content or '<' in content or '《' in content or '_' in content or '[' in content: continue # 舍棄過短或過長的唐詩 lenth = len(content) if lenth < 20 or lenth > 100: continue # 加入列表 poetry_list.append('s' + content + 'e')print '用于訓(xùn)練的唐詩數(shù) : {}'.format(len(poetry_list))poetry_list=sorted(poetry_list,key=lambda x:len(x))words_list = []# 獲取唐詩中所有的字符for poetry in poetry_list: words_list.extend([word for word in poetry])# 統(tǒng)計(jì)其出現(xiàn)的次數(shù)counter = collections.Counter(words_list)# 排序sorted_words = sorted(counter.items(), key=lambda x: x[1], reverse=True)# 獲得出現(xiàn)次數(shù)降序排列的字符列表words_list = ['<unknow>'] + [x[0] for x in sorted_words]# 這里選擇保留高頻詞的數(shù)目,詞只有不到七千個(gè),所以我全部保留words_list = words_list[:len(words_list)]print '詞匯表大小 : {}'.format(words_list)with open(VOCAB_DATA, 'w') as f: for word in words_list: f.write(word + '/n')# 生成單詞到id的映射word_id_dict = dict(zip(words_list, range(len(words_list))))# 將poetry_list轉(zhuǎn)換成向量形式id_list=[]for poetry in poetry_list: id_list.append([str(word_to_id(word,word_id_dict)) for word in poetry])# 將向量寫入文件with open(OUTPUT_DATA, 'w') as f: for id_l in id_list: f.write(' '.join(id_l) + '/n')
新聞熱點(diǎn)
疑難解答
圖片精選