Python文本处理(1)——文本表示之词袋模型(BOW)(1)

极简理论:

词袋(Bag-of-words)模型

词袋(Bag-of-words)是描述文档中单词出现的文本的一种表示形式。它涉及两件方面:

1.已知词汇的词汇表

(构建词汇表的)模型及改进方法:
1.词袋模型(bag-of-words model)
2. n-gram model (n 代表组在一起单词的数量)
比如有,2-gram(bigram) model、3-gram (trigram) model ,1-gram model 其实就相当于 bag-of-words 模型。

2.已知单词存在的一种度量

为已知单词进行评分的方法:
1.存在与否:用二进制来表示单词的存在或不存在。
2.计数:统计每个单词在词汇表中出现的次数
3.词频:计算每个单词在文档中出现的频率

词袋模型处理流程:

  1. 分词
  2. 构建词汇表
  3. 编码

极简实践

相关代码流程:

(使用的scikit-learn)

  • bag of words + 计数
  1. 创建 CountVectorizer 类实例
  2. 调用 fit() 函数:训练数据分词 + 词表的构建
  3. 调用 transform() 函数 :创建数据的词袋表示

notebook代码

import numpy as np
import pandas as pd 

nrows=100
usecols=[0, 6]

df = pd.read_csv('blogtext.csv', usecols=usecols, nrows=nrows)   # 利用参数usecols 只取第1和7列 id 和 text
df
from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer(min_df=3, stop_words='english')     #### ①限制每个词至少在3个文本里出现过,将特征数量大大减少:由6000多减少到400!!②这里使用scikit-learn自带的停止词,又将数量减少到236
vect.fit(data) 
X = vect.transform(data)   # transform方法:创建数据的词袋表示  
X ## 可看到是保存在scipy中的稀疏矩阵(只保存非0元素)中
# # 转换格式
# X.toarray()    # 可以查看其密集的Numpy数组(保存所有0) :使用toarray方法


feature_names = vect.get_feature_names()
print('feature_names:{}'.format(feature_names))
print('num_of_features:{}'.format(len(feature_names)))

再给一个完整的例子:

from sklearn.feature_extraction.text import CountVectorizer
# list of text documents
text = ["The quick brown fox jumped over the lazy dog."]
# create the transform
vectorizer = CountVectorizer()
# tokenize and build vocab
vectorizer.fit(text)
# summarize
print(vectorizer.vocabulary_)
# encode document
vector = vectorizer.transform(text)
# summarize encoded vector
print(vector.shape)
print(type(vector))
print(vector.toarray())

可以参考:
https://machinelearningmastery.com/gentle-introduction-bag-words-model/?spm=a2c4e.10696291.0.0.58b819a400vSSd
https://machinelearningmastery.com/prepare-text-data-machine-learning-scikit-learn/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值