在 python nltk 中查找三元组的条件概率
Finding conditional probability of trigram in python nltk
我已经开始学习 NLTK
并且我正在学习 here 的教程,他们在那里使用像这样的二元组找到条件概率。
import nltk
from nltk.corpus import brown
cfreq_brown_2gram = nltk.ConditionalFreqDist(nltk.bigrams(brown.words()))
不过我想用三元组求条件概率。当我尝试将 nltk.bigrams
更改为 nltk.trigrams
时,出现以下错误。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "home/env/local/lib/python2.7/site-packages/nltk/probability.py", line 1705, in __init__
for (cond, sample) in cond_samples:
ValueError: too many values to unpack (expected 2)
如何使用八卦计算条件概率?
您可以使用描述的 n-gram 模型 here。
用法示例:
from nltk.util import ngrams
input= '...'
N = 3
trigrams = ngrams(input.split(), N)
for grams in trigrams:
print grams
强烈建议您阅读以上文档,希望对您有所帮助。
nltk.ConditionalFreqDist
期望它的数据是 (condition, item)
元组的序列。 nltk.trigrams
returns 长度为 3 的元组,这会导致您 post 编辑的确切错误。
从你的 post 来看,你并不清楚你想使用什么作为条件,但在进行语言建模时的惯例是将最后一个词作为其前身的条件。
以下代码演示了您将如何实现它。
brown_trigrams = nltk.trigrams(brown.words())
condition_pairs = (((w0, w1), w2) for w0, w1, w2 in brown_trigrams)
cfd_brown = nltk.ConditionalFreqDist(condition_pairs)
我已经开始学习 NLTK
并且我正在学习 here 的教程,他们在那里使用像这样的二元组找到条件概率。
import nltk
from nltk.corpus import brown
cfreq_brown_2gram = nltk.ConditionalFreqDist(nltk.bigrams(brown.words()))
不过我想用三元组求条件概率。当我尝试将 nltk.bigrams
更改为 nltk.trigrams
时,出现以下错误。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "home/env/local/lib/python2.7/site-packages/nltk/probability.py", line 1705, in __init__
for (cond, sample) in cond_samples:
ValueError: too many values to unpack (expected 2)
如何使用八卦计算条件概率?
您可以使用描述的 n-gram 模型 here。
用法示例:
from nltk.util import ngrams
input= '...'
N = 3
trigrams = ngrams(input.split(), N)
for grams in trigrams:
print grams
强烈建议您阅读以上文档,希望对您有所帮助。
nltk.ConditionalFreqDist
期望它的数据是 (condition, item)
元组的序列。 nltk.trigrams
returns 长度为 3 的元组,这会导致您 post 编辑的确切错误。
从你的 post 来看,你并不清楚你想使用什么作为条件,但在进行语言建模时的惯例是将最后一个词作为其前身的条件。 以下代码演示了您将如何实现它。
brown_trigrams = nltk.trigrams(brown.words())
condition_pairs = (((w0, w1), w2) for w0, w1, w2 in brown_trigrams)
cfd_brown = nltk.ConditionalFreqDist(condition_pairs)