全新Gensim4.0代码实战(01)-安装与快速上手

简介: 全新Gensim4.0代码实战(01)-安装与快速上手

本节代码地址:https://www.kesci.com/mw/project/600ade02e455800015b7e609


Gensim简介


29.png

Image Name


  • 专门训练词向量的Python接口。 Gensim中的核心算法使用了核心算力,高度优化和并行化的C例程。
  • Gensim可以使用数据流算法处理任意大的语料库。没有“数据集必须适合RAM”的限制。
  • Gensim可在Linux,Windows和OS X以及任何其他支持Python和NumPy的平台上运行。
  • 每天都有成千上万的公司使用Gensim,每周有2600多个学术引用和100万次下载,Gensim是最成熟的ML库之一。
  • Gensim的所有源代码均由GNU LGPL许可证托管在Github上,并由其开源社区维护。有关商业安排,请参阅业务支持。
  • Gensim社区还通过Gensim-data项目发布了针对特定领域(例如法律或健康)的预训练模型。


Gensim安装


安装非常简单;一种是pip另外可以通过conda安装:

  • pip install --upgrade gensim
  • conda install -c conda-forge gensim

In [8]:

!pip install  gensim==4.0.0b0 -i https://pypi.tuna.tsinghua.edu.cn/simple


安装成功


Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting gensim==4.0.0b0
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/d0/86/2d03cb418e9fae6dbc17bafd7524d407be0691a703829cecca23e2bc31a9/gensim-4.0.0b0-cp38-cp38-manylinux1_x86_64.whl (24.0 MB)
     |████████████████████████████████| 24.0 MB 8.7 MB/s eta 0:00:01
Requirement already satisfied: numpy>=1.11.3 in /opt/conda/lib/python3.8/site-packages (from gensim==4.0.0b0) (1.19.1)
Requirement already satisfied: smart-open>=1.8.1 in /opt/conda/lib/python3.8/site-packages (from gensim==4.0.0b0) (4.1.2)
Requirement already satisfied: scipy>=0.18.1 in /opt/conda/lib/python3.8/site-packages (from gensim==4.0.0b0) (1.5.2)
Installing collected packages: gensim
  Attempting uninstall: gensim
    Found existing installation: gensim 3.8.3
    Uninstalling gensim-3.8.3:
      Successfully uninstalled gensim-3.8.3
Successfully installed gensim-4.0.0b0


快速上手


Gensim相关的概念:

  • 文档:一些文本。
  • 语料库:文档的集合。
  • 向量:一种数学上方便的文档表示。
  • 模型:一种将向量从一种表示形式转换为另一种表示形式的算法

import pprint


文档 Document

document = "Human machine interface for lab abc computer applications"


语料 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",
]

# Create a set of frequent words
stoplist = set('for a of the and to in'.split(' '))
# Lowercase each document, split it by white space and filter out stopwords
texts = [[word for word in document.lower().split() if word not in stoplist]
         for document in text_corpus]
# Count word frequencies
from collections import defaultdict
frequency = defaultdict(int)
for text in texts:
    for token in text:
        frequency[token] += 1
# Only keep words that appear more than once
processed_corpus = [[token for token in text if frequency[token] > 1] for text in texts]
pprint.pprint(processed_corpus)

from gensim import corpora
dictionary = corpora.Dictionary(processed_corpus)
print(dictionary)


Dictionary(12 unique tokens: ['computer', 'human', 'interface', 'response', 'survey']...)

向量 Vector

pprint.pprint(dictionary.token2id)

{'computer': 0,
 'eps': 8,
 'graph': 10,
 'human': 1,
 'interface': 2,
 'minors': 11,
 'response': 3,
 'survey': 4,
 'system': 5,
 'time': 6,
 'trees': 9,
 'user': 7}


doc2bow将token转换为id表示,(第一代表单词的索引,第二个代表出现的次数)

new_doc = "Human computer interaction"
new_vec = dictionary.doc2bow(new_doc.lower().split())
print(new_vec)

[(0, 1), (1, 1)]


接下来我们表示所有的文档

bow_corpus = [dictionary.doc2bow(text) for text in processed_corpus]
pprint.pprint(bow_corpus)

[[(0, 1), (1, 1), (2, 1)],
 [(0, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1)],
 [(2, 1), (5, 1), (7, 1), (8, 1)],
 [(1, 1), (5, 2), (8, 1)],
 [(3, 1), (6, 1), (7, 1)],
 [(9, 1)],
 [(9, 1), (10, 1)],
 [(9, 1), (10, 1), (11, 1)],
 [(4, 1), (10, 1), (11, 1)]]


模型 Model


导入Tfidf模型

from gensim import models
# train the model
tfidf = models.TfidfModel(bow_corpus)
# transform the "system minors" string
words = "system minors".lower().split()
print(tfidf[dictionary.doc2bow(words)])


我们可以得到对应词语索引的tfidf值

[(5, 0.5898341626740045), (11, 0.8075244024440723)]


使用tfidf表示所有语料

from gensim import similarities
index = similarities.SparseMatrixSimilarity(tfidf[bow_corpus], num_features=12)


计算查询文档中与所有语料中文档的相似性

query_document = 'system engineering'.split()
query_bow = dictionary.doc2bow(query_document)
sims = index[tfidf[query_bow]]
print(list(enumerate(sims)))


得到所有的相似性

[(0, 0.0), (1, 0.32448703), (2, 0.41707572), (3, 0.7184812), (4, 0.0), (5, 0.0), (6, 0.0), (7, 0.0), (8, 0.0)]

for document_number, score in sorted(enumerate(sims), key=lambda x: x[1], reverse=True):
    print(document_number, score)

3 0.7184812
2 0.41707572
1 0.32448703
0 0.0
4 0.0
5 0.0
6 0.0
7 0.0
8 0.0


相关文章
|
数据采集 自然语言处理 算法
如何使用Python的Gensim库进行自然语言处理和主题建模?
使用Gensim库进行自然语言处理和主题建模,首先通过`pip install gensim`安装库,然后导入`corpora`, `models`等模块。对数据进行预处理,包括分词和去除停用词。接着,创建字典和语料库,使用`Dictionary`和`doc2bow`。之后,应用LDA算法训练模型,设置主题数量并创建`LdaModel`。最后,打印每个主题的主要关键词。可以根据需求调整参数和选择不同算法。
510 0
|
SQL 数据库
若依框架---树状层级部门数据库表
若依框架---树状层级部门数据库表
2104 0
|
网络协议 安全 网络安全
【UDP】——为什么 UDP 数据包不能超过 512 个字节
一开始了解的是 DNS 服务使用的是 UDP 协议,后面看到 DNS 服务主要使用 UDP 协议,在少数情况(传输的数据超过 512 个字节)下也会使用 TCP 协议,因为 UDP 数据包不能超过 512 个字节。那问题来了,为什么 UDP 数据包不能超过 512 个字节呢?
5663 0
【UDP】——为什么 UDP 数据包不能超过 512 个字节
|
机器学习/深度学习 自然语言处理
自然语言处理Transformer模型最详细讲解(图解版)
自然语言处理Transformer模型最详细讲解(图解版)
14436 1
自然语言处理Transformer模型最详细讲解(图解版)
|
12月前
|
消息中间件 存储 运维
RocketMQ监控与运维实战:从底层原理到生产落地全解析
本文深入解析RocketMQ监控与运维体系,涵盖核心架构、关键指标、实战工具及生产最佳实践,助你构建高可用消息系统。
927 4
|
11月前
|
人工智能 智能设计 算法
2026 GEO生成搜索优化技术白皮书:章节详解与案例深度分析
周有贵,GEO专家,深耕AI时代流量入口变革,倡导从SEO到GEO(生成式引擎优化)的认知重构,聚焦“被发现-被理解-被推荐”三层框架,推动企业通过结构化内容、信任资产与平台适配,实现AI信源卡位。
|
人工智能 算法 搜索推荐
AI 搜索时代选 GEO 外援?十家服务商,企业看过来
随着AI普及,GEO(生成式引擎优化)成为品牌获客新赛道。本文推荐10家优质GEO服务商,涵盖内容优化、流量提升、合规风控等方向,助力企业提升在DeepSeek、豆包等AI模型中的曝光与推荐,实现智能时代的精准增长。
|
Ubuntu Linux
"unzip"命令解析:Linux下如何处理压缩文件。
总的来说,`unzip`命令是Linux系统下一款实用而方便的ZIP格式文件处理工具。本文通过简明扼要的方式,详细介绍了在各类Linux发行版上安装 `unzip`的方法,以及如何使用 `unzip`命令进行解压、查看和测试ZIP文件。希望本文章能为用户带来实际帮助,提高日常操作的效率。
4332 12
|
SQL 关系型数据库 MySQL
Flink CDC 3.4 发布, 优化高频 DDL 处理,支持 Batch 模式,新增 Iceberg 支持
Apache Flink CDC 3.4.0 版本正式发布!经过4个月的开发,此版本强化了对高频表结构变更的支持,新增 batch 执行模式和 Apache Iceberg Sink 连接器,可将数据库数据全增量实时写入 Iceberg 数据湖。51位贡献者完成了259次代码提交,优化了 MySQL、MongoDB 等连接器,并修复多个缺陷。未来 3.5 版本将聚焦脏数据处理、数据限流等能力及 AI 生态对接。欢迎下载体验并提出反馈!
2310 1
Flink CDC 3.4 发布, 优化高频 DDL 处理,支持 Batch 模式,新增 Iceberg 支持

热门文章

最新文章