1. 词袋模型(bow bag of words)
one-hot表示方法
- 对语料进行清理,完成分词–大鱼吃小鱼也吃虾米,小鱼吃虾米
- 对每个词进行编号,形成字典–{“大鱼”:1,“吃”:2,“小鱼”:3,“也”:4,“虾米”:5}
- 用0/1代表该词是否出现在文本中,记录成特征向量–[1,1,1,1,1],[0,1,1,0,1],不同考虑词频的问题
- 缺点:不考虑词与词之间的顺序,它假设词与词相互独立,它得到的特征是离散稀疏的
1. 用sklearn库实现
from sklearn.feature_extraction.text import CountVectorizer
countvec = CountVectorizer(min_df=2) #两个以上文档出现的才保留
#文档的词与词之间用空格分隔
x = countvec.fit_transform(['我们 都爱 大 数据','数据 科学 技术部 经济'])
type(x)
scipy.sparse.csr.csr_matrix
x.todense() #将稀疏矩阵直接转换为标准格式矩阵
matrix([[1],
[1]], dtype=int64)
#只存了非零的地方
countvec.get_feature_names()
[‘数据’]
countvec = CountVectorizer()
x = countvec.fit_transform(['我们 都爱 大 数据','数据 科学 技术部 经济'])
x.todense()
matrix([[1, 0, 1, 0, 0, 1],
[0, 1, 1, 1, 1, 0]], dtype=int64)
countvec.get_feature_names()
[‘我们’, ‘技术部’, ‘数据’, ‘科学’, ‘经济’, ‘都爱’]
countvec.vocabulary_
{‘我们’: 0, ‘都爱’: 5, ‘数据’: 2, ‘科学’: 3, ‘技术部’: 1, ‘经济’: 4}
2. 词袋模型的gensim实现
步骤一:建立字典
class gensim.dorpora.dictionary.Dictionary(
documents = None : 若干个被拆成单词集合的文档的集合,一般以list in list 形式出现
prune_at=2000000 : 字典中的最大词条数量
)
import gensim
from gensim.corpora import Dictionary
texts = [['湖北','武汉','Welcome','everyone'],
['hello','world','Hello','BigData','Welcome','everyone']]
dct = Dictionary(texts)
dct.token2id #查看词汇编号结果
{‘Welcome’: 0,
‘everyone’: 1,
‘武汉’: 2,
‘湖北’: 3,
‘BigData’: 4,
‘Hello’: 5,
‘hello’: 6,
‘world’: 7}
dct.dfs #查看每个词汇出现的次数
{3: 1, 2: 1, 0: 2, 1: 2, 6: 1, 7: 1, 5: 1, 4: 1}
dct.num_pos #查看处理过的词汇数量
10
dct.num_nnz #与num_pos类似
10
#增加词条
dct.add_documents([['cat','dog','cute'],['猫','狗','可爱']])
dct.token2id
{‘Welcome’: 0,
‘everyone’: 1,
‘武汉’: 2,
‘湖北’: 3,
‘BigData’: 4,
‘Hello’: 5,
‘hello’: 6,
‘world’: 7,
‘cat’: 8,
‘cute’: 9,
‘dog’: 10,
‘可爱’: 11,
‘狗’: 12,
‘猫’: 13}
#查询词汇在字典中的编码
dct.doc2idx(['This','is','a','cute','cat'])
[-1, -1, -1, 9, 8]
转换为BOW稀疏向量
dct.doc2bow(#转换为BOW格式:list of (token_id,token_count)
document : 用于转化的词条list
allow_update = False : 是否直接更新所用的字典
return_missing = False : 是否返回新出现的(不在字典中的)词
)
输出结果:
[(0,2),(1,2)]:表示在文档中id为0,1的词汇各出现了2次,至于其他词汇则没有出现
return_missing = True时,输出list of (int,int),dict of (str,int)
dct.doc2bow(['This','is','a','cute','cat','cat','and','dog'])
[(8, 2), (10, 1), (17, 1)]
dct.doc2bow(['This','is','a','very','smart','dog'],return_missing=True)
([(10, 1)], {‘This’: 1, ‘a’: 1, ‘is’: 1, ‘smart’: 1, ‘very’: 1})
dct.doc2bow(['This','is','a','very','smart','dog'],
return_missing=True,
allow_update=True)
([(10, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1)],
{‘This’: 1, ‘a’: 1, ‘is’: 1, ‘smart’: 1, ‘very’: 1})
dct.token2id
{‘Welcome’: 0,
‘everyone’: 1,
‘武汉’: 2,
‘湖北’: 3,
‘BigData’: 4,
‘Hello’: 5,
‘hello’: 6,
‘world’: 7,
‘cat’: 8,
‘cute’: 9,
‘dog’: 10,
‘可爱’: 11,
‘狗’: 12,
‘猫’: 13,
‘This’: 14,
‘a’: 15,
‘is’: 16,
‘smart’: 17,
‘very’: 18}
然后再运行一次,结果就不同了
dct.doc2bow(['This','is','a','very','smart','dog'],return_missing=True)
([(10, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1)], {})