Gensim详细介绍和使用:一个Python文本建模库

简介: Gensim详细介绍和使用:一个Python文本建模库

The algorithms in Gensim, such as Word2Vec, FastText, Latent Semantic Indexing (LSI, LSA, LsiModel), Latent Dirichlet Allocation (LDA, LdaModel) etc, automatically discover the semantic structure of documents by examining statistical co-occurrence patterns within a corpus of training documents. These algorithms are unsupervised, which means no human input is necessary – you only need a corpus of plain text documents.

Gensim中的算法,如Word2Verc、FastText、潜在语义索引(LSI、LSA、LsiModel)、潜在狄利克雷分配(LDA、LdaModel)等,通过检查训练文档语料库中的统计共现模式,自动发现文档的语义结构。这些算法是无监督的,这意味着不需要人工输入——你只需要一个纯文本文档的语料库。

一、安装

pip install --upgrade gensim

二、文本预处理

  • Document: 文档,文档字符串 即:“这是一段话”
  • Corpus: 语料,文档字符串列表 即:[“这是一段话”, “这是一段话”]
  • Vector: 向量,应该最好懂 即词在空间中的位置表
  • Bow Corpus:文档分词元组化后的语料列表,元组第一个位置是词对应dictionary的id,第二个是文档中该词出现的次数

2.1 中文语料处理

中文语料:无大小写问题,标点符号问题,词之间无空格,无时态词,需要分词

这里我们使用清华的分词工具Thulac进行分词;

def chinese_process(text_corpus, stoplist=[], k=0, punctuation='"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、\u3000、〃〈〉《》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏﹑﹔·.!?。。'):
    """
    text_corpus: 语料
    stoplist: 需要删除的词
    k:过滤次数小于等于k次的词
    punctuation:需要删除的标点符号
    """
    import thulac
    from collections import defaultdict
    model = thulac.thulac(seg_only=True)
    texts = [[word for word in model.cut(document, text=True).split() if word not in stoplist] for document in text_corpus]
    frequency = defaultdict(int)
    for text in texts:
        for token in text:
            frequency[token] += 1
    processed_corpus = [[token for token in text if frequency[token] > k] for text in texts]
    return processed_corpus

测试:

text_corpus = [
    '实验室abc计算机应用的人机界面',
    '用户对计算机系统响应时间的看法调查',
    'EPS用户界面管理系统',
    'EPS的系统与人系统工程测试',
    '用户感知的响应时间与误差测量的关系',
    '随机二进制无序树的生成',
    '树中路径的交集图',
    '图子Ⅳ树的宽度和井的拟序',
    '图表未成年人调查'
]
print(chinese_process(text_corpus))
# [['实验室', 'abc', '计算机', '应用', '的', '人', '机界', '面'],
#  ['用户', '对', '计算机', '系统', '响应', '时间', '的', '看法', '调查'],
#  ['EPS', '用户', '界面', '管理', '系统'],
#  ['EPS', '的', '系统', '与', '人', '系统工程', '测试'],
#  ['用户', '感知', '的', '响应', '时间', '与', '误差', '测量', '的', '关系'],
#  ['随机', '二进制', '无序', '树', '的', '生成'],
#  ['树', '中', '路径', '的', '交集', '图'],
#  ['图子', 'Ⅳ', '树', '的', '宽度', '和', '井', '的', '拟序'],
#  ['图表', '未成年人', '调查']]

2.2 英文语料处理

英文语料:大小写问题,标点符号问题,词之间有空格, 词有不同形式,需要分词

def english_process(text_corpus, stoplist=[], k=0, punctuation='!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'):
    """
    text_corpus: 语料
    stoplist: 需要删除的词
    k:过滤次数小于等于k次的词
    punctuation:需要删除的标点符号
    """
    from collections import defaultdict
    import re
    texts = [[word for word in re.sub(r'[{}]+'.format(punctuation), '', document).lower().split() if word not in stoplist] for document in text_corpus]
    frequency = defaultdict(int)
    for text in texts:
        for token in text:
            frequency[token] += 1
    processed_corpus = [[token for token in text if frequency[token] > k] for text in texts]
    return processed_corpus

测试:

text_corpus = [
    "Human machine interface for lab abc computer applications",
    "A survey of user opinion of computer system response time",
    "The EPS user interface management system",
    "System and human system engineering testing of EPS",
    "Relation of user perceived response time to error measurement",
    "The generation of random binary unordered trees",
    "The intersection graph of paths in trees",
    "Graph minors IV Widths of trees and well quasi ordering",
    "Graph minors A survey",
]
stoplist = set('for a of the and to in'.split(' '))
print(english_process(text_corpus, stoplist))
# [['human', 'machine', 'interface', 'lab', 'abc', 'computer', 'applications'],
#  ['survey', 'user', 'opinion', 'computer', 'system', 'response', 'time'],
#  ['eps', 'user', 'interface', 'management', 'system'],
#  ['system', 'human', 'system', 'engineering', 'testing', 'eps'],
#  ['relation', 'user', 'perceived', 'response', 'time', 'error', 'measurement'],
#  ['generation', 'random', 'binary', 'unordered', 'trees'],
#  ['intersection', 'graph', 'paths', 'trees'],
#  ['graph', 'minors', 'iv', 'widths', 'trees', 'well', 'quasi', 'ordering'],
#  ['graph', 'minors', 'survey']]

2.3 BOW语料建立

首先把语料进行处理后,得到二维列表,然后将二维列表传入gensim库中的corpus.dictionary模块建立字典,然后根据字典对处理后的语料进行生成BOW语料

text_corpus = [
    "Human machine interface for lab abc computer applications",
    "A survey of user opinion of computer system response time",
    "The EPS user interface management system",
    "System and human system engineering testing of EPS",
    "Relation of user perceived response time to error measurement",
    "The generation of random binary unordered trees",
    "The intersection graph of paths in trees",
    "Graph minors IV Widths of trees and well quasi ordering",
    "Graph minors A survey",
]
# 中文语料处理
text_corpus = chinese_process(text_corpus)
# 建立字典
dictionary = gensim.corpora.Dictionary(text_corpus)
# dictionary.token2id {'abc': 0, '人': 1,'实验室': 2, '应用': 3, ...}
bow_corpus = [dictionary.doc2bow(item) for item in text_corpus]
# [[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1)],
#  [(5, 1), (6, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1)],
#  [(11, 1), (13, 1), (15, 1), (16, 1), (17, 1)],....]

三、模型使用

3.1 word2vec

Word2Vec 是一种词向量模型,它使用浅层神经网络将单词嵌入到低维向量空间中。结果是一组词向量,其中在向量空间中靠近的向量根据上下文具有相似的含义,而彼此相距较远的词向量具有不同的含义。

word2vec 有两种出名的模型,两种加速方式,如果理解可以在此自由配置,

论文实现:Efficient Estimation of Word Representations in Vector Space [CBOW and Skip-gram]

sg : {0, 1}, optional

  Training algorithm: 1 for skip-gram; otherwise CBOW.

hs : {0, 1}, optional

  If 1, hierarchical softmax will be used for model training.

  If 0, hierarchical softmax will not be used for model training.

negative : int, optional

  If > 0, negative sampling will be used, the int for negative specifies how many “noise words” should be drawn (usually between 5-20).

  If 0, negative sampling will not be used.

模型相关代码:

text_corpus = [['实验室', 'abc', '计算机', '应用', '的', '人', '机界', '面'],
 ['用户', '对', '计算机', '系统', '响应', '时间', '的', '看法', '调查']]
 
word2vec = gensim.models.Word2Vec(
    sentences=text_corpus, 
    min_count=1,
    window=3,
    vector_size=100,
)
# 输出word向量
word2vec.wv['中']
# array([ 0.00480066, -0.00362838, -0.00426481,  0.00121976, -0.0041273, ... dtype=float32)
# 计算两个词之间的相似性
word2vec.wv.similarity('图表','图子')
# 0.13703643
# 类似于king-man+woman=queen
word2vec.wv.most_similar(positive=['图子', '图表'], negative=['中'])
# [('系统工程', 0.1806158870458603),('感知', 0.17817144095897675),('界面', 0.13787229359149933),...]
# 找不和其他匹配的项
word2vec.wv.doesnt_match(['图子', '图表', '中'])
# '中'

词向量可视化 这里使用的是TSNE算法进行的降维

from sklearn.manifold import TSNE
import numpy as np
import matplotlib.pyplot as plt
# 中文设置
plt.rcParams['font.sans-serif']=['SimHei'] 
plt.rcParams['axes.unicode_minus']=False
def reduce_dimensions(model):
    num_dimensions = 2
    # 提取vectors和labels
    vectors = np.asarray(model.wv.vectors)
    labels = np.asarray(model.wv.index_to_key)
  # 降维
    tsne = TSNE(n_components=num_dimensions, random_state=0)
    vectors = tsne.fit_transform(vectors)
    x_vals = [v[0] for v in vectors]
    y_vals = [v[1] for v in vectors]
    return x_vals, y_vals, labels
x,y,label = reduce_dimensions(word2vec)
plt.scatter(x,y)
for x_,y_,label_ in zip(x,y,label):
    plt.text(x_, y_, label_)
plt.show()

可视化结果如下:


目录
相关文章
|
存储 人工智能 测试技术
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
本文介绍如何使用LangChain结合DeepSeek实现多轮对话,测开人员可借此自动生成测试用例,提升自动化测试效率。
2471 125
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
|
存储 Web App开发 前端开发
Python + Requests库爬取动态Ajax分页数据
Python + Requests库爬取动态Ajax分页数据
|
监控 数据可视化 数据挖掘
Python Rich库使用指南:打造更美观的命令行应用
Rich库是Python的终端美化利器,支持彩色文本、智能表格、动态进度条和语法高亮,大幅提升命令行应用的可视化效果与用户体验。
1251 0
|
传感器 运维 前端开发
Python离群值检测实战:使用distfit库实现基于分布拟合的异常检测
本文解析异常(anomaly)与新颖性(novelty)检测的本质差异,结合distfit库演示基于概率密度拟合的单变量无监督异常检测方法,涵盖全局、上下文与集体离群值识别,助力构建高可解释性模型。
866 10
Python离群值检测实战:使用distfit库实现基于分布拟合的异常检测
|
数据可视化 关系型数据库 MySQL
【可视化大屏】全流程讲解用python的pyecharts库实现拖拽可视化大屏的背后原理,简单粗暴!
本文详解基于Python的电影TOP250数据可视化大屏开发全流程,涵盖爬虫、数据存储、分析及可视化。使用requests+BeautifulSoup爬取数据,pandas存入MySQL,pyecharts实现柱状图、饼图、词云图、散点图等多种图表,并通过Page组件拖拽布局组合成大屏,支持多种主题切换,附完整源码与视频讲解。
1206 4
【可视化大屏】全流程讲解用python的pyecharts库实现拖拽可视化大屏的背后原理,简单粗暴!
|
运维 Linux 开发者
Linux系统中使用Python的ping3库进行网络连通性测试
以上步骤展示了如何利用 Python 的 `ping3` 库来检测网络连通性,并且提供了基本错误处理方法以确保程序能够优雅地处理各种意外情形。通过简洁明快、易读易懂、实操性强等特点使得该方法非常适合开发者或系统管理员快速集成至自动化工具链之内进行日常运维任务之需求满足。
896 18
|
机器学习/深度学习 API 异构计算
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程
JAX是Google开发的高性能数值计算库,旨在解决NumPy在现代计算需求下的局限性。它不仅兼容NumPy的API,还引入了自动微分、GPU/TPU加速和即时编译(JIT)等关键功能,显著提升了计算效率。JAX适用于机器学习、科学模拟等需要大规模计算和梯度优化的场景,为Python在高性能计算领域开辟了新路径。
1248 0
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程
|
数据采集 存储 Web App开发
Python爬虫库性能与选型实战指南:从需求到落地的全链路解析
本文深入解析Python爬虫库的性能与选型策略,涵盖需求分析、技术评估与实战案例,助你构建高效稳定的数据采集系统。
1101 0
|
存储 监控 安全
Python剪贴板监控实战:clipboard-monitor库的深度解析与扩展应用
本文介绍了基于Python的剪贴板监控技术,结合clipboard-monitor库实现高效、安全的数据追踪。内容涵盖技术选型、核心功能开发、性能优化及实战应用,适用于安全审计、自动化办公等场景,助力提升数据管理效率与安全性。
513 0

推荐镜像

更多