我正在自学如何使用 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
这样的二元组。我也在阅读 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)
关于python - 如何使用 scikit learn 向量化标记的二元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27454767/