Ngram模型及其在NLTK中的困惑

2024-05-19 01:04:50 发布

您现在位置:Python中文网/ 问答频道 /正文

为了把我的问题放在上下文中,我想训练和测试/比较几个(神经)语言模型。为了专注于模型而不是数据准备,我选择使用来自nltk的Brown语料库,并将nltk提供的Ngrams模型作为基线进行训练(将其他LM与之进行比较)。

所以,我的第一个问题实际上是关于nltk的Ngram模型的一个行为,我发现这个行为是可疑的。 因为代码很短,我把它贴在这里:

import nltk

print "... build"
brown = nltk.corpus.brown
corpus = [word.lower() for word in brown.words()]

# Train on 95% f the corpus and test on the rest
spl = 95*len(corpus)/100
train = corpus[:spl]
test = corpus[spl:]

# Remove rare words from the corpus
fdist = nltk.FreqDist(w for w in train)
vocabulary = set(map(lambda x: x[0], filter(lambda x: x[1] >= 5, fdist.iteritems())))

train = map(lambda x: x if x in vocabulary else "*unknown*", train)
test = map(lambda x: x if x in vocabulary else "*unknown*", test)

print "... train"
from nltk.model import NgramModel
from nltk.probability import LidstoneProbDist

estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2) 
lm = NgramModel(5, train, estimator=estimator)

print "len(corpus) = %s, len(vocabulary) = %s, len(train) = %s, len(test) = %s" % ( len(corpus), len(vocabulary), len(train), len(test) )
print "perplexity(test) =", lm.perplexity(test)

我觉得很可疑的是我得到了以下结果:

... build
... train
len(corpus) = 1161192, len(vocabulary) = 13817, len(train) = 1103132, len(test) = 58060
perplexity(test) = 4.60298447026

在4.6的困惑下,Ngram建模在该语料库上似乎非常好。如果我的解释是正确的,那么模型应该能够在平均5次尝试中猜出正确的单词(尽管有13817种可能性…)。如果你能分享一下你对这种困惑的价值的经验(我真的不相信)?我在网上没有发现任何关于nltk的ngram模型的抱怨(但也许我做错了)。对于Ngram模型和计算难题,您知道NLTK的一个很好的替代方案吗?

谢谢!


Tags: thelambdain模型testimportlentrain
1条回答
网友
1楼 · 发布于 2024-05-19 01:04:50

你得到一个低困惑,因为你正在使用五角星模型。如果您使用bigram模型,您的结果将在50-1000(或大约5-10位)的更规则范围内。

根据你的评论,你是在使用NLTK-3.0alpha吗?你不应该,至少在语言建模方面不应该:

https://github.com/nltk/nltk/issues?labels=model

事实上,整个model模块已经从NLTK-3.0a4预发行版中删除,直到问题得到解决。

相关问题 更多 >

    热门问题