如何使用scikit-learn对标记的二元组进行向量化?

我在自学如何使用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这样的二元组进行向量化?我还在阅读关于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)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注