我在自学如何使用scikit-learn,并决定开始第二个任务,但使用我自己的语料库。我手动获得了一些二元组,假设是这样的:
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 CountVectorizercount_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
这样的二元组进行向量化?我还在阅读关于dictvectorizer和Sklearn-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)