其官方文档给出的解释如下:sklearn.feature_extraction.text.CountVectorizer — scikit-learn 1.0.1 documentation
我的个人理解为:将文本文档转化为token计数矩阵。并且如果不提供先验词典,也不使用进行某种特征选择的分析器,则特征的数量将等于通过分析数据找到的词汇表大小。下面附上我的实验结果,下文用到的vocabulary_方法是生成文本与其对应特征索引的映射。“this”的特征索引为8.“and”为0.从中我们也可以看到,数据的排序是按字母顺序。具体的参数信息可以查看《深入浅出Pytorch——从模型到源码》P254、P255.
通过实验结果分析我们可以看到,我们生成了一个CountVectorizer()类的对象vectorizer。并且应用他的fit_transfrom()方法将其转为为token的计数矩阵后输出(关于fit_transfrom()方法,可以查看我的另外一篇博客【sklearn】StandardScaler()及其fit_transform()方法_m0_58810879的博客-CSDN博客)。我们可以看到输出矩阵的的每一行代表着其对应的文本数据中该行每个单词出现的频次。 最后通过vocabulary_方法输出文本与特征索引的映射。
计算TF-IDF特征的两种方法如下:
关于IF-IDF特征tf-idf_百度百科
一种是TfidfVectorizer,另一种是CountVectorizer +TfidfTransformer 。
from sklearn.feature_extraction.text import CountVectorizer , TfidfTransformer , TfidfVectorizer
vectorizer = CountVectorizer()
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document',]
X = vectorizer.fit_transform(corpus)
# print(X.toarray())
# print(vectorizer.vocabulary_)
transformer = TfidfTransformer()
print(transformer)
X1 = transformer.fit_transform(X)
print(X1.toarray())
print('='*60)
vectorizer = TfidfVectorizer()
print(vectorizer)
X2 = vectorizer.fit_transform(corpus)
print(X2)