用LSTM写古诗词

本文介绍了使用LSTM模型创作古诗词的方法,首先统计古诗词的词频建立词与数字的对应关系,然后构建2层LSTM结构的模型,每个LSTM层包含128个单元,最后设置学习率等相关参数进行模型训练。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:整体思路就是先统计古诗词中的词频,进行词到数字的映射。生成poems_vector(词向量),word_to_int(词数字映射关系),words(词表)。

预处理古诗词代码:

import collections
import numpy as  np

def   process_poems(file_path):
    poems = []

    with  open(file_path,'r',encoding='utf-8') as f:
        for line in f.readlines():
            title,content = line.strip().split(":")
            if '_'  in content  or "(" in content or ")" in content or "{" in content or "}" in content:
                continue
            if len(content)  <5 or len(content) > 100 :
                continue
            content = 'G' + content + 'E'
            poems.append(content)
        all_words = []
        for poem in  poems:
            all_words+=[word for word in poem]
        #print(all_words)
        counter = collections.Counter(all_words)
        counter_pairs = counter.most_common()
        words,_ = zip(*counter_pairs)  #词汇表
        word_to_int = dict()  #每个字的映射
        for word   in words:
            word_to_int[word] = len(word_to_int)

        #获得每行诗的向量
        poems_vector =   [list(map(lambda  word : word_to_int.get(word,len(words)) ,poem))for poem in poems ]
        word_to_int[' '] = len(word_to_int)+1


        return poems_vector,word_to_int,words




def generate_batch(batch_size,poems_vector,word_to_int):
    n_chunk = len(po
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值