如何使用scikit学习标记的双字母组织?

tum*_*eed 4 python nlp machine-learning nltk scikit-learn

我正在自学如何使用scikit-learn,我决定开始第二项任务但是用我自己的语料库.我手工获得了一些二重奏,让我们说:

training_data = [[('this', 'is'), ('is', 'a'),('a', 'text'), 'POS'],
[('and', 'one'), ('one', 'more'), 'NEG']
[('and', 'other'), ('one', 'more'), 'NEU']]
Run Code Online (Sandbox Code Playgroud)

我想以一种格式对它们进行矢量化,这种格式可以很好地填写scikit-learn(svc,多项式朴素贝叶斯等)提供的一些分类算法.这是我试过的:

from sklearn.feature_extraction.text import CountVectorizer

count_vect = CountVectorizer(analyzer='word')

X = count_vect.transform(((' '.join(x) for x in sample)
                  for sample in training_data))

print X.toarray()
Run Code Online (Sandbox Code Playgroud)

这个问题是我不知道如何处理标签(即'POS', 'NEG', 'NEU'),我是否需要"矢量化"标签,以便传递training_data给分类算法,或者我可以让它像'POS'或任何其他那种字符串?另一个问题是我得到了这个:

raise ValueError("Vocabulary wasn't fitted or is empty!")
ValueError: Vocabulary wasn't fitted or is empty!
Run Code Online (Sandbox Code Playgroud)

那么,我怎样才能将bigrams像矢量化一样training_data.我也在阅读有关dictvectorizerSklearn-pandas的文章,你们认为使用它们对于这个任务来说可能是更好的方法吗?

ely*_*ase 7

它应该如下所示:

>>> training_data = [[('this', 'is'), ('is', 'a'),('a', 'text'), 'POS'],
                 [('and', 'one'), ('one', 'more'), 'NEG'],
                 [('and', 'other'), ('one', 'more'), 'NEU']]
>>> count_vect = CountVectorizer(preprocessor=lambda x:x,
                                 tokenizer=lambda x:x)
>>> X = count_vect.fit_transform(doc[:-1] for doc in training_data)

>>> print count_vect.vocabulary_
{('and', 'one'): 1, ('a', 'text'): 0, ('is', 'a'): 3, ('and', 'other'): 2, ('this', 'is'): 5, ('one', 'more'): 4}
>>> print X.toarray()
[[1 0 0 1 0 1]
 [0 1 0 0 1 0]
 [0 0 1 0 1 0]]
Run Code Online (Sandbox Code Playgroud)

然后将标签放在目标变量中:

y = [doc[-1] for doc in training_data] # ['POS', 'NEG', 'NEU']
Run Code Online (Sandbox Code Playgroud)

现在你可以训练一个模型:

model = SVC()
model.fit(X, y)
Run Code Online (Sandbox Code Playgroud)