极简理论:
词袋(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.词频:计算每个单词在文档中出现的频率
词袋模型处理流程:
- 分词
- 构建词汇表
- 编码
极简实践
相关代码流程:
(使用的scikit-learn)
- bag of words + 计数
- 创建 CountVectorizer 类实例
- 调用 fit() 函数:训练数据分词 + 词表的构建
- 调用 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/

——文本表示之词袋模型(BOW)(1)&spm=1001.2101.3001.5002&articleId=103599437&d=1&t=3&u=2a0f196f4c1542df8ebcf793a5daaf54)
1389

被折叠的 条评论
为什么被折叠?



