微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

training_data = [[('this', 'is'), ('is', 'a'),('a', 'text'), 'POS'],
[('and', 'one'), ('one', 'more'), 'NEG']
[('and', 'other'), ('one', 'more'), 'NEU']]

我想以一种格式对它们进行矢量化,这种格式可以很好地填充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()

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

raise ValueError("Vocabulary wasn't fitted or is empty!")
ValueError: Vocabulary wasn't fitted or is empty!

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

解决方法:

它应该如下所示:

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

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

y = [doc[-1] for doc in training_data] # ['POS', 'NEG', 'NEU']

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

model = SVC()
model.fit(X, y)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐