0

我正在尝试在文本语料库上训练三元语言模型并希望执行 KN 平滑。显然,“nltk.trigrams”在字符级别执行此操作。我想知道如何在单词级别做到这一点并执行 KN 平滑。这是我编写的一段代码,但不起作用:

    with open('file.txt',"r",encoding = "ISO-8859-1") as ff:
        text = ff.read()

    word_tok = tknzr.tokenize(text)
    ngrams = nltk.trigrams(word_tok)
    freq_dist = nltk.FreqDist(ngrams)
    kneser_ney = nltk.KneserNeyProbDist(freq_dist)
    print(kneser_ney.prob('you go to'))

我得到错误:

    Expected an iterable with 3 members.
4

1 回答 1

0

换行:

print(kneser_ney.prob('you go to'))

和:

print(kneser_ney.prob('you go to'.split()))

然后它工作正常。当使用从古腾堡项目下载的小说“白鲸记”中的文本作为训练文件时,我得到的值为 0.05217391304347826

通过此修改,您的代码将类似于以下内容:

with open('./txts/mobyDick.txt') as ff:
    text = ff.read()


from nltk import word_tokenize,trigrams
from nltk import FreqDist, KneserNeyProbDist


word_tok = word_tokenize(text)
ngrams = trigrams(word_tok)
freq_dist = FreqDist(ngrams)
kneser_ney = KneserNeyProbDist(freq_dist)
print(kneser_ney.prob('you go to'.split()))

此外,这里的所有内容都是在单词级别完成的,而不是在字符级别:

ngrams = trigrams(word_tok)
for _ in range(0,10):
    print(next(ngrams))

#('\ufeff', 'The', 'Project')
#('The', 'Project', 'Gutenberg')
#('Project', 'Gutenberg', 'EBook')
#('Gutenberg', 'EBook', 'of')
#('EBook', 'of', 'Moby')
#('of', 'Moby', 'Dick')
#('Moby', 'Dick', ';')
#('Dick', ';', 'or')
#(';', 'or', 'The')
#('or', 'The', 'Whale')

频率分布也在单词级别:

freq_dist.freq(tuple('on the ocean'.split()))
#7.710783916846906e-06
freq_dist.freq(tuple('new Intel CPU'.split()))
#0.0


于 2020-01-12T16:29:46.087 回答