gpt4 book ai didi

python - NLTK 语言建模混淆

转载 作者:太空宇宙 更新时间:2023-11-04 09:33:01 25 4
gpt4 key购买 nike

我想在 python 中使用 NLTK 训练语言模型,但我遇到了几个问题。首先,我不知道为什么当我写这样的东西时我的文字变成了字符:

s = "Natural-language processing (NLP) is an area of computer science " \
"and artificial intelligence concerned with the interactions " \
"between computers and human (natural) languages."
s = s.lower();


paddedLine = pad_both_ends(word_tokenize(s),n=2);

train, vocab = padded_everygram_pipeline(2, paddedLine)
print(list(vocab))
lm = MLE(2);
lm.fit(train,vocab)

打印的词汇是这样的,显然是不正确的(我不想使用字符!),这是输出的一部分。:

<s>', '<', 's', '>', '</s>', '<s>', 'n', 'a', 't', 'u', 'r', 'a', 'l', '-', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e', '</s>', '<s>', 'p', 'r', 'o', 'c', 'e', 's', 's', 'i', 'n', 'g', '</s>', '<s>', '(', '</s>', '<s>', 'n', 'l', 'p', '</s>', '<s>', ')', '</s>'

为什么我的输入变成了字符?我以另一种方式完成了这项工作,但没有运气:

paddedLine = pad_both_ends(word_tokenize(s),n=2);
#train, vocab = padded_everygram_pipeline(2, tokens)
#train = everygrams(paddedLine,max_len = 2);

train = ngrams(paddedLine,2);
vocab = Vocabulary(paddedLine,unk_cutoff = 1);
print(list(train))

lm = MLE(2);
lm.fit(train,vocab)

当我运行这段代码时,我的火车什么都没有,空的!它显示我“[]”!有线的事情是当我从上面的代码在这一行评论时:

vocab = Vocabulary(paddedLine,unk_cutoff = 1);

现在我的火车数据没问题,像这样的东西是正确的:

[('<s>', 'natural-language'), ('natural-language', 'processing'), ('processing', '('), ('(', 'nlp'), ('nlp', ')'), (')', 'is'), ('is', 'an'), ('an', 'area'), ('area', 'of'), ('of', 'computer'), ('computer', 'science'), ('science', 'and'), ('and', 'artificial'), ('artificial', 'intelligence'), ('intelligence', 'concerned'), ('concerned', 'with'), ('with', 'the'), ('the', 'interactions'), ('interactions', 'between'), ('between', 'computers'), ('computers', 'and'), ('and', 'human'), ('human', '('), ('(', 'natural'), ('natural', ')'), (')', 'languages'), ('languages', '.'), ('.', '</s>')]

有什么问题吗?顺便说一句,我不得不说我不是 python 或 NLTK 方面的专家,这是我的第一次体验。下一个问题是如何在训练语言模型上使用 kneser-ney 平滑或加一平滑?我是否以正确的方式进行语言模型培训?我的训练数据很简单:

"Natural-language processing (NLP) is an area of computer science " \
"and artificial intelligence concerned with the interactions " \
"between computers and human (natural) languages."

谢谢。

最佳答案

padded_everygram_pipeline 函数需要一个 n-gram 列表。您应该按如下方式修复您的第一个代码片段。此外,python 生成器是惰性序列,您不能多次迭代它们。

from nltk import word_tokenize
from nltk.lm import MLE
from nltk.lm.preprocessing import pad_both_ends, padded_everygram_pipeline

s = "Natural-language processing (NLP) is an area of computer science " \
"and artificial intelligence concerned with the interactions " \
"between computers and human (natural) languages."
s = s.lower()

paddedLine = [list(pad_both_ends(word_tokenize(s), n=2))]

train, vocab = padded_everygram_pipeline(2, paddedLine)

lm = MLE(2)

lm.fit(train, vocab)

print(lm.counts)

关于python - NLTK 语言建模混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com