CountVectorizer#

class sklearn.feature_extraction.text.CountVectorizer(*, input='content', encoding='utf-8', decode_error='strict', strip_accents=None, lowercase=True, preprocessor=None, tokenizer=None, stop_words=None, token_pattern='(?u)\\b\\w\\w+\\b', ngram_range=(1, 1), analyzer='word', max_df=1.0, min_df=1, max_features=None, vocabulary=None, binary=False, dtype=<class 'numpy.int64'>)[source]#

将文本文档集合转换为标记计数矩阵。

此实现使用 scipy.sparse.csr_matrix 生成计数稀疏表示。

如果您没有提供先验词典,并且没有使用进行某种特征选择的分析器,那么特征的数量将等于通过分析数据找到的词汇量大小。

有关不同特征提取器效率比较,请参阅 FeatureHasher 和 DictVectorizer 比较

用户指南 中阅读更多内容。

参数:
input{‘filename’, ‘file’, ‘content’}, default=’content’
  • 如果为 'filename',则传递给 fit 的序列参数预计是一个文件名列表,需要读取这些文件以获取要分析的原始内容。

  • 如果为 'file',则序列项必须具有一个 ‘read’ 方法(类似文件对象),该方法用于获取内存中的字节。

  • 如果为 'content',则输入预计是类型为字符串或字节的项序列。

encodingstr, default=’utf-8’

如果给定要分析的字节或文件,则使用此编码进行解码。

decode_error{‘strict’, ‘ignore’, ‘replace’}, default=’strict’

如果给定要分析的字节序列包含给定 encoding 中没有的字符,则应如何处理。默认情况下,它是 ‘strict’,表示将引发 UnicodeDecodeError。其他值为 ‘ignore’ 和 ‘replace’。

strip_accents{‘ascii’, ‘unicode’} or callable, default=None

在预处理步骤中删除重音并执行其他字符规范化。‘ascii’ 是一种快速方法,仅适用于具有直接 ASCII 映射的字符。‘unicode’ 是一种稍慢的方法,适用于任何字符。None(默认值)表示不执行字符规范化。

‘ascii’ 和 ‘unicode’ 都使用来自 unicodedata.normalize 的 NFKD 规范化。

lowercasebool, default=True

在标记化之前将所有字符转换为小写。

preprocessorcallable, default=None

覆盖预处理(strip_accents 和 lowercase)阶段,同时保留标记化和 n-gram 生成步骤。仅当 analyzer 不可调用时适用。

tokenizercallable, default=None

覆盖字符串标记化步骤,同时保留预处理和 n-gram 生成步骤。仅当 analyzer == 'word' 时适用。

stop_words{‘english’}, list, default=None

如果为 ‘english’,则使用内置的英语停用词列表。‘english’ 存在一些已知问题,您应该考虑替代方案(请参阅 使用停用词)。

如果是一个列表,则假定该列表包含停用词,所有这些停用词都将从生成的标记中删除。仅当 analyzer == 'word' 时适用。

如果为 None,则不使用停用词。在这种情况下,将 max_df 设置为更高的值(例如在 (0.7, 1.0) 范围内)可以根据词项在语料库内文档频率自动检测和过滤停用词。

token_patternstr or None, default=r”(?u)\b\w\w+\b”

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

如果 token_pattern 中有一个捕获组,则捕获组内容而不是整个匹配项将成为标记。最多允许一个捕获组。

ngram_rangetuple (min_n, max_n), default=(1, 1)

用于提取不同词 n-gram 或字符 n-gram 的 n 值范围的下限和上限。所有满足 min_n <= n <= max_n 的 n 值都将使用。例如,ngram_range(1, 1) 意味着仅使用 unigrams,(1, 2) 意味着使用 unigrams 和 bigrams,而 (2, 2) 意味着仅使用 bigrams。仅当 analyzer 不可调用时适用。

analyzer{‘word’, ‘char’, ‘char_wb’} or callable, default=’word’

特征是应该由词 n-gram 还是字符 n-gram 构成。选项 ‘char_wb’ 仅从词边界内的文本创建字符 n-gram;词边缘的 n-gram 用空格填充。

如果传递可调用对象,则用于从原始、未处理的输入中提取特征序列。

版本 0.21 中的更改。

自 v0.21 起,如果 inputfilenamefile,数据首先从文件中读取,然后传递给给定的可调用分析器。

max_dffloat in range [0.0, 1.0] or int, default=1.0

构建词汇表时,忽略文档频率严格高于给定阈值(特定于语料库的停用词)的词项。如果是浮点数,则参数表示文档的比例,如果是整数,则表示绝对计数。如果 vocabulary 不为 None,则忽略此参数。

min_dffloat in range [0.0, 1.0] or int, default=1

构建词汇表时,忽略文档频率严格低于给定阈值的词项。此值在文献中也称为截止值。如果是浮点数,则参数表示文档的比例,如果是整数,则表示绝对计数。如果 vocabulary 不为 None,则忽略此参数。

max_featuresint, default=None

如果不是 None,则构建一个词汇表,其中只考虑按语料库中词频排序的前 max_features 个特征。否则,使用所有特征。

如果 vocabulary 不为 None,则忽略此参数。

vocabularyMapping or iterable, default=None

可以是映射(例如字典),其中键是词项,值是特征矩阵中的索引,也可以是词项上的可迭代对象。如果未给出,则从输入文档中确定词汇表。映射中的索引不应重复,且在 0 和最大索引之间不应有任何间隙。

binarybool, default=False

如果为 True,则所有非零计数都设置为 1。这对于建模二元事件而不是整数计数的离散概率模型很有用。

dtypedtype, default=np.int64

fit_transform() 或 transform() 返回的矩阵类型。

属性:
vocabulary_dict

词项到特征索引的映射。

fixed_vocabulary_bool

如果用户提供了从词项到索引的固定词汇表映射,则为 True。

另请参阅

HashingVectorizer

将文本文档集合转换为标记计数矩阵。

TfidfVectorizer

将原始文档集合转换为 TF-IDF 特征矩阵。

示例

>>> from sklearn.feature_extraction.text import CountVectorizer
>>> corpus = [
...     'This is the first document.',
...     'This document is the second document.',
...     'And this is the third one.',
...     'Is this the first document?',
... ]
>>> vectorizer = CountVectorizer()
>>> X = vectorizer.fit_transform(corpus)
>>> vectorizer.get_feature_names_out()
array(['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third',
       'this'], ...)
>>> print(X.toarray())
[[0 1 1 1 0 0 1 0 1]
 [0 2 0 1 0 1 1 0 1]
 [1 0 0 1 1 0 1 1 1]
 [0 1 1 1 0 0 1 0 1]]
>>> vectorizer2 = CountVectorizer(analyzer='word', ngram_range=(2, 2))
>>> X2 = vectorizer2.fit_transform(corpus)
>>> vectorizer2.get_feature_names_out()
array(['and this', 'document is', 'first document', 'is the', 'is this',
       'second document', 'the first', 'the second', 'the third', 'third one',
       'this document', 'this is', 'this the'], ...)
 >>> print(X2.toarray())
 [[0 0 1 1 0 0 1 0 0 0 0 1 0]
 [0 1 0 1 0 1 0 1 0 0 1 0 0]
 [1 0 0 1 0 0 0 0 1 1 0 1 0]
 [0 0 1 0 1 0 1 0 0 0 0 0 1]]
build_analyzer()[source]#

返回一个可调用对象来处理输入数据。

此可调用对象处理预处理、标记化和 n-gram 生成。

返回:
analyzer: callable

用于处理预处理、标记化和 n-gram 生成的函数。

build_preprocessor()[source]#

返回一个在标记化之前预处理文本的函数。

返回:
preprocessor: callable

在标记化之前预处理文本的函数。

build_tokenizer()[source]#

返回一个将字符串拆分为标记序列的函数。

返回:
tokenizer: callable

将字符串拆分为标记序列的函数。

decode(doc)[source]#

将输入解码为 unicode 符号字符串。

解码策略取决于 vectorizer 参数。

参数:
docbytes or str

要解码的字符串。

返回:
doc: str

unicode 符号字符串。

fit(raw_documents, y=None)[source]#

学习原始文档中所有标记的词汇表字典。

参数:
raw_documentsiterable

生成 str、unicode 或文件对象的可迭代对象。

yNone

此参数被忽略。

返回:
selfobject

拟合后的 vectorizer。

fit_transform(raw_documents, y=None)[source]#

学习词汇表字典并返回文档-词项矩阵。

这等同于先 fit 后 transform,但实现效率更高。

参数:
raw_documentsiterable

生成 str、unicode 或文件对象的可迭代对象。

yNone

此参数被忽略。

返回:
Xarray of shape (n_samples, n_features)

文档-词项矩阵。

get_feature_names_out(input_features=None)[source]#

获取转换的输出特征名称。

参数:
input_featuresarray-like of str or None, default=None

Not used, present here for API consistency by convention.

返回:
feature_names_outstr 对象的 ndarray

转换后的特征名称。

get_metadata_routing()[source]#

获取此对象的元数据路由。

请查阅 用户指南,了解路由机制如何工作。

返回:
routingMetadataRequest

封装路由信息的 MetadataRequest

get_params(deep=True)[source]#

获取此估计器的参数。

参数:
deepbool, default=True

如果为 True,将返回此估计器以及包含的子对象(如果它们是估计器)的参数。

返回:
paramsdict

参数名称映射到其值。

get_stop_words()[source]#

构建或获取有效的停用词列表。

返回:
stop_words: list or None

停用词列表。

inverse_transform(X)[source]#

返回 X 中具有非零条目的每个文档的词项。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

文档-词项矩阵。

返回:
X_originallist of arrays of shape (n_samples,)

词项数组列表。

set_params(**params)[source]#

设置此估计器的参数。

此方法适用于简单的估计器以及嵌套对象(如 Pipeline)。后者具有 <component>__<parameter> 形式的参数,以便可以更新嵌套对象的每个组件。

参数:
**paramsdict

估计器参数。

返回:
selfestimator instance

估计器实例。

transform(raw_documents)[source]#

将文档转换为文档-词项矩阵。

使用 fit 拟合的词汇表或提供给构造函数的词汇表,从原始文本文档中提取标记计数。

参数:
raw_documentsiterable

生成 str、unicode 或文件对象的可迭代对象。

返回:
Xsparse matrix of shape (n_samples, n_features)

文档-词项矩阵。