在 Python 中结合 CountVectorizer 和 ngrams

Ale*_*tin 1 python nltk scikit-learn countvectorizer

有一项使用 ngrams 对男性和女性名字进行分类的任务。所以,有一个数据框,如:

    name    is_male
Dorian      1
Jerzy       1
Deane       1
Doti        0
Betteann    0
Donella     0
Run Code Online (Sandbox Code Playgroud)

具体要求是使用

from nltk.util import ngrams
Run Code Online (Sandbox Code Playgroud)

对于这个任务,创建 ngrams (n=2,3,4)

我列了一个名字列表,然后使用了 ngrams:

from nltk.util import ngrams
from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()

test_ngrams = []
for name in name_list:
    test_ngrams.append(list(ngrams(name,3)))
Run Code Online (Sandbox Code Playgroud)

现在我需要以某种方式矢量化所有这些以用于分类,我尝试

X_train = count_vect.fit_transform(test_ngrams)
Run Code Online (Sandbox Code Playgroud)

收到:

AttributeError: 'list' object has no attribute 'lower'
Run Code Online (Sandbox Code Playgroud)

我知道这里的列表是错误的输入类型,有人可以解释我应该怎么做,所以我以后可以使用 MultinomialNB,例如。我这样做是否正确?提前致谢!

Jan*_*nes 6

您正在将一系列列表传递给矢量化器,这就是您收到AttributeError. 相反,您应该传递一个可迭代的字符串。从CountVectorizer 文档:

fit_transform(raw_documents,y=无)

学习词汇词典并返回术语文档矩阵。

这等效于 fit 后跟 transform,但更有效地实现。

参数: raw_documents:可迭代

产生 str、 unicode 或 file 对象的可迭代对象。

要回答您的问题,CountVectorizer可以使用ngram_range以下方法创建 N-gram (以下生成双元组):

count_vect = CountVectorizer(ngram_range=(2,2))

corpus = [
    'This is the first document.',
    'This is the second second document.',
]
X = count_vect.fit_transform(corpus)

print(count_vect.get_feature_names())
['first document', 'is the', 'second document', 'second second', 'the first', 'the second', 'this is']
Run Code Online (Sandbox Code Playgroud)

更新:

由于您提到必须使用 NLTK 生成 ngram,因此我们需要覆盖CountVectorizer. 即,analyzer将原始字符串转换为特征的 :

分析器:字符串、{'word'、'char'、'char_wb'} 或可调用

[...]

如果传递了一个可调用对象,它将用于从未处理的原始输入中提取特征序列。

由于我们已经提供了 ngrams,一个身份函数就足够了:

count_vect = CountVectorizer(
    analyzer=lambda x:x
)
Run Code Online (Sandbox Code Playgroud)

结合 NLTK ngrams 和 CountVectorizer 的完整示例:

corpus = [
    'This is the first document.',
    'This is the second second document.',
]

def build_ngrams(text, n=2):
    tokens = text.lower().split()
    return list(nltk.ngrams(tokens, n))

corpus = [build_ngrams(document) for document in corpus]

count_vect = CountVectorizer(
    analyzer=lambda x:x
)

X = count_vect.fit_transform(corpus)
print(count_vect.get_feature_names())
[('first', 'document.'), ('is', 'the'), ('second', 'document.'), ('second', 'second'), ('the', 'first'), ('the', 'second'), ('this', 'is')]
Run Code Online (Sandbox Code Playgroud)