CountVectorizer() 对单个字母单词不起作用

假设我需要对以下数据应用 CountVectorizer():

words = [     'A am is',     'This the a',     'the am is',     'this a am',]

我做了以下操作:

from sklearn.feature_extraction.text import CountVectorizervectorizer = CountVectorizer()X = vectorizer.fit_transform(corpus)print(X.toarray())

它返回以下结果:

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

作为参考,print(vectorizer.get_feature_names()) 输出 ['am', 'is', 'the', 'this']

为什么 ‘a’ 没有被读取?
是否是因为单个字母的单词在 CountVectorizer() 中不被视为单词?


回答:

查看 文档

token_pattern

表示什么构成“token”的正则表达式,仅在 analyzer == ‘word’ 时使用。默认的正则表达式选择 2 个或更多字母数字字符的 token(标点符号被完全忽略,并始终被视为 token 分隔符)。

默认的 tokenizer 忽略所有单字符 token。这就是为什么 a 缺失的原因。

如果你希望单字符 token 包含在词汇表中,那么你需要使用自定义 tokenizer。

示例代码

from sklearn.feature_extraction.text import CountVectorizervectorizer = CountVectorizer(tokenizer=lambda txt: txt.split())X = vectorizer.fit_transform(words)print (vectorizer.get_feature_names())

输出:

['a', 'am', 'is', 'the', 'this']

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

发表回复

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