How to Develop Word Embeddings in Python with Gensim

https://machinelearningmastery.com/develop-word-embeddings-python-gensim/

本教程分为 6 个部分;他们是:

词嵌入

Gensim 库

开发 Word2Vec 嵌入

可视化单词嵌入

加载 Google 的 Word2Vec 嵌入

加载斯坦福大学的 GloVe 嵌入

词嵌入

单词嵌入是一种提供单词的密集向量表示的方法,这些单词捕获了有关其含义的某些信息。

单词嵌入是对更简单的词袋模型单词编码方案(如字数统计和频率)的改进,这些方案会导致描述文档但不描述单词含义的大而稀疏的向量(大多数为 0 个值)。

单词嵌入的工作原理是使用算法基于大型文本语料库训练一组固定长度的密集和连续值向量。每个单词都由嵌入空间中的一个点表示,这些点是根据目标单词周围的单词学习和移动的。

Gensim Python 库

gensim 4.0 版本和3.0版本在语法上差别很大
https://github.com/piskvorky/gensim/wiki/Migrating-from-Gensim-3.x-to-4
word2vector
https://nlp.stanford.edu/projects/glove/

对于自然语言工作者,glove 比 word2vector 更受欢迎

开发word2vector

python 复制代码
from gensim.models import Word2Vec
# define training data
sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
 ['this', 'is', 'the', 'second', 'sentence'],
 ['yet', 'another', 'sentence'],
 ['one', 'more', 'sentence'],
 ['and', 'the', 'final', 'sentence']]
# train model
model = Word2Vec(sentences, min_count=1)
# summarize the loaded model
print(model)
# summarize vocabulary
words = list(model.wv.key_to_index)
print(words)
# access vector for one word
print(model.wv['sentence'])
# save model
model.save('model.bin')
# load model
new_model = Word2Vec.load('model.bin')
print(new_model)

可视化单词嵌入

clike 复制代码
from sklearn.decomposition import PCA
from matplotlib import pyplot
from gensim.models import Word2Vec
# define training data
sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
 ['this', 'is', 'the', 'second', 'sentence'],
 ['yet', 'another', 'sentence'],
 ['one', 'more', 'sentence'],
 ['and', 'the', 'final', 'sentence']]
# train model
model = Word2Vec(sentences, min_count=1)
# fit a 2D PCA model to the vectors
X = model.wv[model.wv.key_to_index]
pca = PCA(n_components=2)
result = pca.fit_transform(X)
# create a scatter plot of the projection
pyplot.scatter(result[:, 0], result[:, 1])
words = list(model.wv.key_to_index)
for i, word in enumerate(words):
 pyplot.annotate(word, xy=(result[i, 0], result[i, 1]))
pyplot.show()
相关推荐
七夜zippoe6 分钟前
启元 Q1 腿部运动学逆解:Python 算站立下蹲关节角
开发语言·python·ai·机器人·腿部运动学
熊猫钓鱼>_>10 分钟前
精准碰一碰近场分享与拖拽投送实战:把文件“碰“进另一台设备【鸿蒙心迹】
开发语言·华为·harmonyos·鸿蒙·openharmony
第404号工位14 分钟前
插上充电宝真能偷光相册?我拆解了一台改装充电宝,实测“恶意充电”的真实攻击链
linux·python·架构
技术卷40 分钟前
Windows 下自定义 MCP 踩坑:stdin 默认继承导致 CPython 启动阻塞
python·mcp·zcode
小oo呆43 分钟前
【学习心得】Python多进程
python·操作系统
CodeGL1 小时前
9、Python基础之IO编程
开发语言·数据库·python
HySpark1 小时前
ERes2Net声纹识别短音频匹配不稳定:从音频时长到有效音素的排查实践
python·语音识别·声纹识别·vad·eres2net
TomEval1 小时前
【测AI】第17篇:大模型评测方法论 —— LLM 怎么测?
人工智能·python·aigc·测试用例
fanruitian1 小时前
python 进程 线程
java·前端·python
曹牧1 小时前
SVN:失联项目
开发语言