我可以在scikit-learn中使用CountVectorizer来统计未用于提取标记的文档的频率吗?

我一直在使用scikit-learn中的CountVectorizer类进行工作。

我明白,如果按照下面的方式使用,最终输出将包含特征或标记的计数数组。

这些标记是从一组关键词中提取的,例如:

tags = [  "python, tools",  "linux, tools, ubuntu",  "distributed systems, linux, networking, tools",]

下一步是:

from sklearn.feature_extraction.text import CountVectorizervec = CountVectorizer(tokenizer=tokenize)data = vec.fit_transform(tags).toarray()print data

我们得到的结果是:

[[0 0 0 1 1 0] [0 1 0 0 1 1] [1 1 1 0 1 0]]

这很好,但我的情况略有不同。

我想以相同的方式提取特征,但我不想让data中的行与提取特征的文档相同。

换句话说,如何统计另一组文档的计数,例如:

list_of_new_documents = [  ["python, chicken"],  ["linux, cow, ubuntu"],  ["machine learning, bird, fish, pig"]]

并得到:

[[0 0 0 1 0 0] [0 1 0 0 0 1] [0 0 0 0 0 0]]

我阅读了CountVectorizer类的文档,并发现了vocabulary参数,它是术语到特征索引的映射。然而,我似乎无法利用这个参数来解决我的问题。

任何建议都将不胜感激。
PS: 以上示例的所有功劳归于Matthias Friedrich的博客


回答:

你是对的,vocabulary正是你需要的。它是这样工作的:

>>> cv = sklearn.feature_extraction.text.CountVectorizer(vocabulary=['hot', 'cold', 'old'])>>> cv.fit_transform(['pease porridge hot', 'pease porridge cold', 'pease porridge in the pot', 'nine days old']).toarray()array([[1, 0, 0],       [0, 1, 0],       [0, 0, 0],       [0, 0, 1]], dtype=int64)

所以你传递一个字典,其中包含你想要的特征作为键。

如果你在一组文档上使用了CountVectorizer,然后你想将这些文档的特征集用于一组新的文档,可以使用原始CountVectorizer的vocabulary_属性,并将其传递给新的CountVectorizer。所以在你的例子中,你可以这样做:

newVec = CountVectorizer(vocabulary=vec.vocabulary_)

来创建一个使用第一个CountVectorizer词汇表的新标记器。

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中创建了一个多类分类项目。该项目可以对…

发表回复

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