scikit-learn:CountVectorizer提取词频

本文深入解析了sklearn库中CountVectorizer的使用方法与参数配置,详细介绍了如何通过此工具进行文本预处理,包括去除停用词、转换大小写、提取n-gram等,以及如何根据需求调整参数以优化文本特征提取过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer

 

sklearn.feature_extraction.text.CountVectorizer(

input=u'content', encoding=u'utf-8', decode_error=u'strict',strip_accents=None, lowercase=True, preprocessor=None, tokenizer=None, stop_words=None,token_pattern=u'(?u)\b\w\w+\b', ngram_range=(1, 1), analyzer=u'word', max_df=1.0, min_df=1,max_features=None, vocabulary=None, binary=False, dtype=)

作用:Convert a collection of text documents to a matrix of token counts(计算词汇的数量,即tf);结果由 scipy.sparse.coo_matrix进行稀疏表示。

 

看下参数就知道CountVectorizer在提取tf时都做了什么:

strip_accents : {‘ascii’, ‘unicode’, None}:是否除去“音调”,不知道什么是“音调”?看:http://textmechanic.com/?reqp=1&reqr=nzcdYz9hqaSbYaOvrt==

lowercase : boolean, True by default:计算tf前,先将所有字符转化为小写。这个参数一般为True。

preprocessor : callable or None (default):复写the preprocessing (string transformation) stage,但保留tokenizing and n-grams generation steps.这个参数可以自己写。

tokenizer : callable or None (default):复写the string tokenization step,但保留preprocessing and n-grams generation steps.这个参数可以自己写。

stop_words : string {‘english’}, list, or None (default):如果是‘english’, a built-in stop word list for English is used。如果是a list,那么最终的tokens中将去掉list中的所有的stop word。如果是None, 不处理停顿词;但参数 max_df可以设置为 [0.7, 1.0) 之间,进而根据intra corpus document frequency(df) of terms自动detect and filter stop words。这个参数要根据自己的需求调整。

token_pattern : string:正则表达式,默认筛选长度大于等于2的字母和数字混合字符(select tokens of 2 or more alphanumeric characters ),参数analyzer设置为word时才有效。

ngram_range : tuple (min_n, max_n):n-values值得上下界,默认是ngram_range=(1, 1),该范围之内的n元feature都会被提取出来!这个参数要根据自己的需求调整。

analyzer : string, {‘word’, ‘char’, ‘char_wb’} or callable:特征基于wordn-grams还是character n-grams。如果是callable是自己复写的从the raw, unprocessed input提取特征的函数。

max_df : float in range [0.0, 1.0] or int, default=1.0: min_df : float in range [0.0, 1.0] or int, default=1:按比例,或绝对数量删除df超过max_df或者df小于min_df的word tokens。有效的前提是参数vocabulary设置成Node。

max_features : int or None, default=None:选择tf最大的max_features个特征。有效的前提是参数vocabulary设置成Node。

vocabulary : Mapping or iterable, optional:自定义的特征word tokens,如果不是None,则只计算vocabulary中的词的tf。还是设为None靠谱。

binary : boolean, default=False:如果是True,tf的值只有0和1,表示出现和不出现,useful for discrete probabilistic models that model binary events rather than integer counts.。

dtype : type, optional:Type of the matrix returned by fit_transform() or transform().。

结论: CountVectorizer提取tf都做了这些:去音调、转小写、去停顿词、在word(而不是character,也可自己选择参数)基础上提取所有ngram_range范围内的特征,同时删去满足“max_df, min_df,max_features”的特征的tf。当然,也可以选择tf为binary。

最后看下两个函数:

fit(raw_documents[, y]) Learn a vocabulary dictionary of all tokens in the raw documents.

fit_transform(raw_documents[, y]) Learn the vocabulary dictionary and return term-document matrix.

 

转自:https://blog.youkuaiyun.com/mmc2015/article/details/46866537?utm_source=copy 

 

from sklearn.feature_extraction.text import CountVectorizer

texts=["dog cat fish","dog cat cat","fish bird", 'bird']
cv = CountVectorizer()
cv_fit=cv.fit_transform(texts)

print((cv.get_feature_names()))
print(cv.vocabulary_)  # 索引

print((cv_fit.toarray()))
print('对应特征总个数:', (cv_fit.toarray().sum(axis=0)))  # .sum(axis=0)按列求和

### scikit-learn在自然语言处理中的应用 scikit-learn虽然不是一个专门针对自然语言处理(NLP)设计的库,但在NLP任务中仍然扮演着重要角色。该库提供了多种工具来帮助构建基于文本的数据分析流程,包括但不限于文本向量化、分类模型训练以及评估指标计算。 #### 文本预处理与特征提取 对于任何NLP项目而言,第一步通常是对原始文档集合执行必要的清理操作并将其转换成适合输入给机器学习算法的形式。scikit-learn内置了`CountVectorizer`类用于将文本数据转化为词频矩阵;还有`TfidfTransformer`或更方便使用的`TfidfVectorizer`可以直接创建TF-IDF加权后的稀疏表示形式[^1]。 ```python from sklearn.feature_extraction.text import TfidfVectorizer corpus = [ 'This is the first document.', 'This document is the second document.', 'And this is the third one.', 'Is this the first document?' ] vectorizer = TfidfVectorizer() X = vectorizer.fit_transform(corpus) print(vectorizer.get_feature_names_out()) print(X.shape) ``` #### 构建分类器 一旦有了经过适当变换后的数值型特征表示之后,就可以利用诸如朴素贝叶斯(`MultinomialNB`)、支持向量机(SVM)`LinearSVC`等经典监督式学习方法来进行情感分析、主题识别等工作。下面是一个简单的例子展示如何使用逻辑回归(Logistic Regression)完成垃圾邮件过滤的任务: ```python from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report # 假设我们已经有了标记好的电子邮件样本集 emails 和对应的标签 labels emails_train, emails_test, labels_train, labels_test = train_test_split(emails, labels, test_size=0.2, random_state=42) text_clf = Pipeline([ ('tfidf', TfidfVectorizer()), ('clf', LogisticRegression(max_iter=1000)) ]) text_clf.fit(emails_train, labels_train) predictions = text_clf.predict(emails_test) print(classification_report(labels_test, predictions)) ``` 上述代码片段展示了如何组合管道(Pipeline),使得整个工作流更加简洁高效——从文本清洗直到最终预测结果生成都可以在一个对象内自动完成。 #### 数据归一化的重要性 值得注意的是,在某些情况下可能还需要考虑对已经获得的特征向量进一步做标准化处理,比如当不同维度间存在数量级差异较大时。尽管大多数时候直接采用默认参数下的`TfidfVectorizer`就足够好用了,但如果后续要接入其他类型的ML模型,则建议先尝试引入像`StandardScaler`这样的组件来做额外调整[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值