sta*_*kit 12 python dictionary nlp linguistics nltk
nltk或任何其他NLP工具是否允许基于输入句子构造概率树,从而将输入文本的语言模型存储在字典树中,以下示例给出了粗略的想法,但我需要相同的功能,使得单词Wt可以不仅仅是对过去的输入词(历史)Wt-n进行概率建模,而且还对Wt + m等前瞻性词进行概率建模.此外,回顾和前瞻字数也应该是2或更多,即bigrams或更多.python中有没有其他库可以实现这个目的?
from collections import defaultdict
import nltk
import math
ngram = defaultdict(lambda: defaultdict(int))
corpus = "The cat is cute. He jumps and he is happy."
for sentence in nltk.sent_tokenize(corpus):
tokens = map(str.lower, nltk.word_tokenize(sentence))
for token, next_token in zip(tokens, tokens[1:]):
ngram[token][next_token] += 1
for token in ngram:
total = math.log10(sum(ngram[token].values()))
ngram[token] = {nxt: math.log10(v) - total for nxt, v in ngram[token].items()}
Run Code Online (Sandbox Code Playgroud)
解决方案需要前瞻和回顾,特殊的子类字典可能有助于解决这个问题.也可以指向谈论实现这样一个系统的相关资源.nltk.models似乎做了类似的事情,但已不再可用.NLP中是否存在实现此想法的现有设计模式?基于跳过克的模型也类似于这个想法,但我觉得这应该已经在某处实现了.
如果我正确理解你的问题,那么你正在寻找一种方法来预测一个单词在给定其周围上下文(不仅是后向上下文,还有前向上下文)的情况下的概率。满足您的目的的一种快速方法是训练两种不同的语言模型。一个从右到左,另一个从左到右,然后给定上下文的单词的概率将是前向和后向上下文的归一化总和。
扩展您的代码:
from collections import defaultdict
import nltk
from nltk.tokenize import word_tokenize
import numpy as np
ngram = defaultdict(lambda: defaultdict(int))
ngram_rev = defaultdict(lambda: defaultdict(int)) #reversed n-grams
corpus = "The cat is cute. He jumps and he is happy."
for sentence in nltk.sent_tokenize(corpus):
tokens = map(str.lower, nltk.word_tokenize(sentence))
for token, next_token in zip(tokens, tokens[1:]):
ngram[token][next_token] += 1
for token, rev_token in zip(tokens[1:], tokens):
ngram_rev[token][rev_token] += 1
for token in ngram:
total = np.log(np.sum(ngram[token].values()))
total_rev = np.log(np.sum(ngram_rev[token].values()))
ngram[token] = {nxt: np.log(v) - total
for nxt, v in ngram[token].items()}
ngram_rev[token] = {prv: np.log(v) - total_rev
for prv, v in ngram_rev[token].items()}
Run Code Online (Sandbox Code Playgroud)
现在上下文位于 ngram 和 ngram_rev 中,它们分别保存前向和后向上下文。
您还应该考虑平滑。也就是说,如果给定的短语在您的训练语料库中没有出现,您将得到零概率。为了避免这种情况,有许多平滑技术,其中最简单的是附加平滑。