Python实战:用nltk库5步搭建你的第一个n-gram文本生成器(附古诗生成案例)
Python实战用nltk库5步搭建你的第一个n-gram文本生成器附古诗生成案例在自然语言处理领域文本生成一直是个令人着迷的话题。想象一下计算机能够模仿人类写作风格创作出连贯的文字这背后离不开语言模型的支撑。而n-gram作为最基础却实用的语言模型之一至今仍在许多场景中发挥着重要作用。本文将带你从零开始用Python的nltk库实现一个完整的n-gram文本生成器并以《全唐诗》为例教你生成具有古典韵味的诗句。1. 环境准备与数据加载首先确保你的Python环境已安装nltk库。如果尚未安装可以通过以下命令快速获取pip install nltk接下来我们需要准备语料数据。对于中文文本生成分词是首要步骤。nltk默认不支持中文分词因此需要额外配置import nltk nltk.download(punkt) # 下载分词数据包 # 中文分词示例 from nltk.tokenize import word_tokenize text 举头望明月低头思故乡 print(word_tokenize(text)) # 英文分词器对中文效果不佳注意对于中文处理推荐使用jieba等专用分词工具。这里我们先用英文语料演示基础原理后续再处理中文古诗案例。加载nltk自带的英文小说《爱丽丝梦游仙境》作为练习语料from nltk.corpus import gutenberg alice gutenberg.words(carroll-alice.txt) print(f语料包含{len(alice)}个单词)2. 理解n-gram的核心原理n-gram模型基于一个简单假设一个词的出现概率只与它前面的n-1个词相关。这种马尔可夫性质使得模型计算变得可行。让我们通过具体例子理解不同n值的影响n值模型名称依赖长度生成特点1unigram0完全独立2bigram1考虑前一个词3trigram2考虑前两个词4n-gramn-1更长上下文更连贯但稀疏构建n-gram模型的关键是计算条件概率。例如bigram概率公式为P(w_i | w_{i-1}) count(w_{i-1}, w_i) / count(w_{i-1})用Python实现一个简单的频率统计from collections import defaultdict def build_ngram_model(text, n2): model defaultdict(lambda: defaultdict(int)) for i in range(len(text)-n1): *context, target text[i:in] model[tuple(context)][target] 1 return model # 示例统计 sample_text I love NLP and I love coding.split() print(build_ngram_model(sample_text, 2))3. 完整n-gram生成器实现现在我们将各个组件整合成一个完整的文本生成器。以下是核心类实现import random from collections import defaultdict class NGramGenerator: def __init__(self, n3): self.n n self.model defaultdict(lambda: defaultdict(int)) self.start_tokens [] def train(self, corpus): # 记录所有句子开头作为起始点 self.start_tokens [tuple(sent[:self.n-1]) for sent in corpus if len(sent) self.n-1] # 构建n-gram统计模型 for sent in corpus: for i in range(len(sent)-self.n1): *context, target sent[i:iself.n] self.model[tuple(context)][target] 1 def generate(self, max_len20, start_contextNone): # 选择初始上下文 if start_context: context start_context else: context random.choice(self.start_tokens) output list(context) # 逐步生成文本 for _ in range(max_len): if context not in self.model: break next_words list(self.model[context].items()) weights [count for word, count in next_words] words [word for word, count in next_words] # 按概率随机选择下一个词 next_word random.choices(words, weightsweights, k1)[0] output.append(next_word) # 更新上下文 context tuple(output[-(self.n-1):]) return .join(output)使用方法示例# 准备训练数据已分词的句子列表 corpus [ I love natural language processing.split(), Natural language processing is amazing.split(), I love to write Python code.split() ] # 创建并训练trigram模型 generator NGramGenerator(n3) generator.train(corpus) # 生成文本 print(generator.generate(max_len10))4. 中文古诗生成实战现在让我们挑战更有趣的任务——生成中文古诗。这需要几个特殊处理中文分词使用jieba进行精确分词语料预处理清洗和格式化古诗文本韵律处理考虑平仄和押韵规则首先准备《全唐诗》语料假设已保存为quan_tang_shi.txtimport jieba def load_poems(file_path): with open(file_path, r, encodingutf-8) as f: poems [line.strip() for line in f if line.strip()] # 分词处理保留标点以维持古诗结构 segmented [] for poem in poems: words jieba.lcut(poem) segmented.append([w for w in words if w.strip()]) return segmented poems load_poems(quan_tang_shi.txt)调整生成策略以适应古诗特点class PoemGenerator(NGramGenerator): def __init__(self, n3): super().__init__(n) self.line_breaks [] # 记录诗句换行位置 def train(self, corpus): super().train(corpus) # 记录诗句结构信息 for poem in corpus: line_pos [i for i, word in enumerate(poem) if word in (, 。)] self.line_breaks.extend(line_pos) def generate(self, max_len20): output super().generate(max_len) # 按古诗格式添加换行 words output.split() for pos in sorted(random.sample(self.line_breaks, k2)): if pos len(words): words.insert(pos, \n) return .join(words)生成示例poem_gen PoemGenerator(n4) poem_gen.train(poems) for _ in range(3): print(poem_gen.generate()) print(---)5. 进阶优化与问题解决实际应用中可能会遇到以下常见问题及解决方案5.1 数据稀疏问题当n较大时许多n-gram组合在训练中从未出现导致生成中断。解决方法包括回退策略当高阶n-gram不存在时使用低阶模型平滑技术如Add-k平滑给所有可能组合赋予小概率实现回退生成def generate_with_backoff(self, max_len20): context random.choice(self.start_tokens) output list(context) for _ in range(max_len): current_n self.n while current_n 1: current_context tuple(output[-(current_n-1):]) if current_context in self.model: next_words list(self.model[current_context].items()) weights [count for word, count in next_words] words [word for word, count in next_words] next_word random.choices(words, weightsweights, k1)[0] output.append(next_word) break current_n - 1 else: # 连unigram都不存在时随机选择 next_word random.choice(list(self.model[tuple()].keys())) output.append(next_word) return .join(output)5.2 生成多样性控制不同的采样策略会产生不同风格的文本策略实现方式效果特点贪婪采样总是选择概率最大的词保守但可能重复随机采样完全按概率分布随机选择多样但可能不连贯Top-k采样只在概率最高的k个词中随机选平衡多样性与质量温度采样调整概率分布的陡峭程度控制创新程度实现温度采样def generate_with_temperature(self, temp1.0, max_len20): context random.choice(self.start_tokens) output list(context) for _ in range(max_len): if context not in self.model: break next_words list(self.model[context].items()) words, counts zip(*next_words) probs np.array(counts) ** (1/temp) probs probs / probs.sum() next_word np.random.choice(words, pprobs) output.append(next_word) context tuple(output[-(self.n-1):]) return .join(output)5.3 生成质量评估自动评估生成文本的质量是个挑战。一些实用方法包括人工评估最可靠但成本高困惑度计算衡量模型对测试数据的预测能力重复率统计检测生成中的重复片段语义连贯性使用现代语言模型评估计算bigram困惑度的示例import math def calculate_perplexity(test_data, model): total_log_prob 0 total_words 0 for sent in test_data: for i in range(1, len(sent)): context tuple(sent[max(0,i-1):i]) target sent[i] context_counts sum(model[context].values()) if context in model and target in model[context]: prob model[context][target] / context_counts else: prob 1e-10 # 避免log(0) total_log_prob math.log(prob) total_words 1 perplexity math.exp(-total_log_prob / total_words) return perplexity在实际项目中我经常发现n3或4的模型在连贯性和多样性之间取得了较好的平衡。对于古诗生成配合适当的后处理如强制押韵可以显著提升质量。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2433748.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!