如何基于gensim和Sklearn实现文本矢量化

大家利用机器学习或深度学习开展文本分类或关联性分析之前,由于计算机只能分析数值型数据,而人类所熟悉的自然语言文字,机器学习算法是一窍不通的,因此需要将大类的文本及前后关系进行设计,并将其转换为数值化表示。一般来说,文本语言模型主要有词袋模型(BOW)、词向量模型和主题模型,目前比较常见是前两种,各种机器学习框架都有相应的word2vec的机制和支持模型,比如gensim和Scikit-learn(简称Sklearn),词袋模型向量化技术主要有One-Hot、文本计数数值化、词频-逆文档频率(TF-IDF)。详见以下示例,分别讲述了上述两种框架下的应用,同时结合了分词技术,去掉了停用词,加入了自定义分词。具体如下,供大家学习参考。
一、运行环境: python3.10环境,安装了 sklearn、gensim、jieba等。
**二、应用示例:**实现多段文本的自动分词,之后进行词袋模型的矢量化表示。完整代码如下。

python 复制代码
from sklearn.feature_extraction import DictVectorizer  
from sklearn.feature_extraction.text import CountVectorizer  
from sklearn.feature_extraction.text import TfidfVectorizer  
from gensim.models import Word2Vec  
import gensim  
import jieba,sys  
# 将当前目录加载道path
sys.path.append("../") 
# 加载自定义分词词典  
jieba.load_userdict("../data/user_dict.txt")  
  
# 去掉一些停用词和数字  
def rm_tokens(words,stwlist):  
    words_list = list(words)  
    stop_words = stwlist  
    for i in range(words_list.__len__())[::-1]:  
        if words_list[i] in stop_words: # 去除停用词  
            words_list.pop(i)  
        elif len(words_list[i]) == 1:  # 去除单个字符  
            words_list.pop(i)  
        elif words_list[i] == " ":  # 去除空字符  
            words_list.pop(i)  
        elif words_list[i].strip() == "/" or words_list[i].strip()  == "\\" or words_list[i].strip()  == "'" or words_list[i].strip()  == "\"":  # 去斜杠  
            words_list.pop(i)  
    return words_list  

# 进行分词并返回
def cut_words(text):  
    result = rm_tokens(jieba.cut(text),stwlist)  
    print('list(jieba.cut(text))结果为:', result)  
    txt = ' '.join(result)  
    return txt  
# 创建停用词列表  
def get_stop_words(path=r'../data/user_stopwords.txt'):  
    file = open(path, 'r',encoding='utf-8').read().split('\n')  
    return set(file)  
  
# 2 获取停用词  
stwlist = get_stop_words()  
  
#类别向量数值化方式  
data = [  
{'name': 'Alan Turing', 'born': 1912, 'died': 1954},  
{'name': 'Herbert A. Simon', 'born': 1916, 'died': 2001},  
{'name': 'Jacek Karpinski', 'born': 1927, 'died': 2010},  
{'name': 'J.C.R. Licklider', 'born': 1915, 'died': 1990},  
{'name': 'Marvin Minsky', 'born': 1927, 'died': 2016},  
]

#1.One-Hot编码,文本矢量化或数值化表示  
vec = DictVectorizer(sparse=False, dtype=int)  
print(vec.fit_transform(data))  
print(vec.get_feature_names())  
vec = DictVectorizer(sparse=True, dtype=int) #One-Hot编码,设置稀疏矩阵的紧凑表示  
data2=vec.fit_transform(data)  

sample=[  
    '列出了aaa井的基本数据信息,描述了该井所在地区的钻探成果和钻井简况',  
    '列出了bbb井的基本数据信息及下x深结构图,详细记录了自拖航至,弃井作业,综合录井日记',  
    '列出了ccc井的基本数据信息,描述了该井所在地区的钻探成果和钻井简况'  
]  
sample2 = []  
for i in sample:  
    sample2.append(cut_words(i))  
  
#2.文本计数的数值化转换表示  
vec = CountVectorizer(lowercase=False,stop_words=None,analyzer='word') #文本计数的数值化转换  
X = vec.fit_transform(sample2)  
print(vec.get_feature_names())  
print(X.toarray())  
print("词袋 = ",vec.vocabulary_)   #词袋,根据分词结果和首字母,进行编号  

#3.词频-逆文档频率,文本矢量化或数值化表示  
vec = TfidfVectorizer(lowercase=False,stop_words=None,analyzer='word', use_idf=True,smooth_idf=True) #词频-逆文档频率  
X = vec.fit_transform(sample2)  
print(vec.get_feature_names())  
'基本数据信息' in vec.get_feature_names() #判断是否包含指定字符串  
print(X.toarray()) #输出词向量
  
# 4.gensim的词袋模型  
# 需要将数据放在Dictionary中,带有unicode token  
sample2_unitoken = [d.split() for d in sample2]  
dictionary = gensim.corpora.Dictionary(sample2_unitoken)  
vec = [dictionary.doc2bow(word) for word in sample2_unitoken]  
print(vec)   #输出词向量
  
# 5.gensim的n-gram模型  
bigram = gensim.models.Phrases(sample2_unitoken)  
txts = [bigram[line] for line in sample2_unitoken]  
dictionary = gensim.corpora.Dictionary(txts)  
vec = [dictionary.doc2bow(text) for text in txts]  
print(vec)   #输出词向量
  
# 6.gensim的tfidf模型  
dictionary = gensim.corpora.Dictionary(sample2_unitoken)  
doc2bow = [dictionary.doc2bow(word) for word in sample2_unitoken]  
tfidf=gensim.models.TfidfModel(doc2bow)  
vec=[]  
for document in tfidf[doc2bow]:  
    vec.append(document)  
print(vec)  #输出词向量
相关推荐
yuanmazhiwu8 小时前
计算机毕业设计:Python智慧出行数据分析与模式识别系统 Django框架 可视化 数据分析 PyEcharts 交通 深度学习(建议收藏)✅
人工智能·python·算法·数据分析·django·flask·课程设计
bKYP953cL8 小时前
Flask - 常见应用部署方案
后端·python·flask
Dream of maid9 小时前
Python-基础1(数据类型)
开发语言·python
清水白石0089 小时前
《从缓存到数据库:一致性之痛与工程之道》
数据库·python·缓存
Thomas.Sir9 小时前
第三章:Agent智能体开发实战之【LlamaIndex 工作流从入门到实战】
python·ai·llama·workflow·llamaindex
小江的记录本9 小时前
【JEECG Boot】JEECG Boot 系统性知识体系全方位结构化总结
java·前端·spring boot·后端·python·spring·spring cloud
SomeB1oody9 小时前
【Python深度学习】1.2. 多层感知器MLP(人工神经网络)实现非线性分类理论
开发语言·人工智能·python·深度学习·机器学习·分类
清水白石0089 小时前
《从同步到消息驱动:现代后端交互模式的深度解析与工程实践》
python·交互
deephub10 小时前
机器学习特征工程:缩放、编码、聚合、嵌入与自动化
人工智能·python·机器学习·特征工程
科雷软件测试14 小时前
Python中itertools.product:快速生成笛卡尔积
开发语言·python