1

有一个任务是使用 ngram 对男性和女性的名字进行分类。所以,有一个像这样的数据框:

    name    is_male
Dorian      1
Jerzy       1
Deane       1
Doti        0
Betteann    0
Donella     0

具体要求是使用

from nltk.util import ngrams

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

我列出了一个名字,然后使用了 ngram:

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)))

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

X_train = count_vect.fit_transform(test_ngrams)

收到:

AttributeError: 'list' object has no attribute 'lower'

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

4

1 回答 1

6

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

fit_transform(raw_documents, y=None)

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

这相当于先拟合后变换,但更有效地实现。

参数: raw_documents:可迭代

产生 str、 unicode 或文件对象的迭代。

要回答您的问题,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']

更新:

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

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

[...]

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

由于我们已经提供了 ngram,一个恒等函数就足够了:

count_vect = CountVectorizer(
    analyzer=lambda x:x
)

结合 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')]
于 2017-12-19T19:54:53.730 回答