深度学习从入门到精通——词向量介绍及应用

词向量介绍

  • 词向量(Word embedding),即把词语表示成实数向量。“好”的词向量能体现词语直接的相近关系。词向量已经被证明可以提高NLP任务的性能,例如语法分析和情感分析。
  • 词向量与词嵌入技术的提出是为了解决onehot的缺陷。它把每个词表示成连续稠密的向量,能较好地表达不同词之间的关联关系。
  • 如果两个词是关联的,那么这两个词分别对应的词向量的余弦相似度越接近于1。如果两个词关联关系比较小,那么这两个词分别对应的词向量的余弦相似度越接近于0.
    在这里插入图片描述

1.1 加载TokenEmbedding

TokenEmbedding()参数

  • embedding_name
    将模型名称以参数形式传入TokenEmbedding,加载对应的模型。默认为w2v.baidu_encyclopedia.target.word-word.dim300的词向量。
  • unknown_token
    未知token的表示,默认为[UNK]。
  • unknown_token_vector
    未知token的向量表示,默认生成和embedding维数一致,数值均值为0的正态分布向量。
  • extended_vocab_path
    扩展词汇列表文件路径,词表格式为一行一个词。如引入扩展词汇列表,trainable=True。
  • trainable
    Embedding层是否可被训练。True表示Embedding可以更新参数,False为不可更新。默认为True。
  • dim300代表该词向量维度大小为300.

这里参考的预训练embedding 包括以下:
在这里插入图片描述

EMBEDDING_NAME_LIST = [# Word2Vec# baidu_encyclopedia"w2v.baidu_encyclopedia.target.word-word.dim300","w2v.baidu_encyclopedia.target.word-character.char1-1.dim300","w2v.baidu_encyclopedia.target.word-character.char1-2.dim300","w2v.baidu_encyclopedia.target.word-character.char1-4.dim300","w2v.baidu_encyclopedia.target.word-ngram.1-2.dim300","w2v.baidu_encyclopedia.target.word-ngram.1-3.dim300","w2v.baidu_encyclopedia.target.word-ngram.2-2.dim300","w2v.baidu_encyclopedia.target.word-wordLR.dim300","w2v.baidu_encyclopedia.target.word-wordPosition.dim300","w2v.baidu_encyclopedia.target.bigram-char.dim300","w2v.baidu_encyclopedia.context.word-word.dim300","w2v.baidu_encyclopedia.context.word-character.char1-1.dim300","w2v.baidu_encyclopedia.context.word-character.char1-2.dim300","w2v.baidu_encyclopedia.context.word-character.char1-4.dim300","w2v.baidu_encyclopedia.context.word-ngram.1-2.dim300","w2v.baidu_encyclopedia.context.word-ngram.1-3.dim300","w2v.baidu_encyclopedia.context.word-ngram.2-2.dim300","w2v.baidu_encyclopedia.context.word-wordLR.dim300","w2v.baidu_encyclopedia.context.word-wordPosition.dim300",# wikipedia"w2v.wiki.target.bigram-char.dim300","w2v.wiki.target.word-char.dim300","w2v.wiki.target.word-word.dim300","w2v.wiki.target.word-bigram.dim300",# people_daily"w2v.people_daily.target.bigram-char.dim300","w2v.people_daily.target.word-char.dim300","w2v.people_daily.target.word-word.dim300","w2v.people_daily.target.word-bigram.dim300",# weibo"w2v.weibo.target.bigram-char.dim300","w2v.weibo.target.word-char.dim300","w2v.weibo.target.word-word.dim300","w2v.weibo.target.word-bigram.dim300",# sogou"w2v.sogou.target.bigram-char.dim300","w2v.sogou.target.word-char.dim300","w2v.sogou.target.word-word.dim300","w2v.sogou.target.word-bigram.dim300",# zhihu"w2v.zhihu.target.bigram-char.dim300","w2v.zhihu.target.word-char.dim300","w2v.zhihu.target.word-word.dim300","w2v.zhihu.target.word-bigram.dim300",# finacial"w2v.financial.target.bigram-char.dim300","w2v.financial.target.word-char.dim300","w2v.financial.target.word-word.dim300","w2v.financial.target.word-bigram.dim300",# literature"w2v.literature.target.bigram-char.dim300","w2v.literature.target.word-char.dim300","w2v.literature.target.word-word.dim300","w2v.literature.target.word-bigram.dim300",# siku"w2v.sikuquanshu.target.word-word.dim300","w2v.sikuquanshu.target.word-bigram.dim300",# Mix-large"w2v.mixed-large.target.word-char.dim300","w2v.mixed-large.target.word-word.dim300",# GOOGLE NEWS"w2v.google_news.target.word-word.dim300.en",# GloVe"glove.wiki2014-gigaword.target.word-word.dim50.en","glove.wiki2014-gigaword.target.word-word.dim100.en","glove.wiki2014-gigaword.target.word-word.dim200.en","glove.wiki2014-gigaword.target.word-word.dim300.en","glove.twitter.target.word-word.dim25.en","glove.twitter.target.word-word.dim50.en","glove.twitter.target.word-word.dim100.en","glove.twitter.target.word-word.dim200.en",# FastText"fasttext.wiki-news.target.word-word.dim300.en","fasttext.crawl.target.word-word.dim300.en",
]
from paddlenlp.embeddings import TokenEmbedding# 初始化TokenEmbedding, 预训练embedding未下载时会自动下载并加载数据
token_embedding = TokenEmbedding(embedding_name="w2v.baidu_encyclopedia.target.word-word.dim300")# 查看token_embedding详情
print(token_embedding)

在这里插入图片描述

1.2 认识一下Embedding

TokenEmbedding.search()

在这里插入图片描述

1.3 单词相似度对比

TokenEmbedding.cosine_sim()
计算词向量间余弦相似度,语义相近的词语余弦相似度更高,说明预训练好的词向量空间有很好的语义表示能力。


score1 = token_embedding.cosine_sim("女孩", "女人")
score2 = token_embedding.cosine_sim("女孩", "书籍")
print('score1:', score1)
print('score2:', score2)

在这里插入图片描述

2. 基于TokenEmbedding衡量句子语义相似度

在许多实际应用场景(如文档检索系统)中, 需要衡量两个句子的语义相似程度。此时我们可以使用词袋模型(Bag of Words,简称BoW)计算句子的语义向量。
首先,将两个句子分别进行切词,并在TokenEmbedding中查找相应的单词词向量(word embdding)。
然后,根据词袋模型,将句子的word embedding叠加作为句子向量(sentence embedding)。
最后,计算两个句子向量的余弦相似度。

2.1 基于TokenEmbedding的词袋模型

使用BoWEncoder搭建一个BoW模型用于计算句子语义。

  • paddlenlp.TokenEmbedding组建word-embedding层
  • paddlenlp.seq2vec.BoWEncoder组建句子建模层
  • 通过词袋编码和余弦相似度计算来评估两个文本之间的相似度
class BoWModel(nn.Layer):def __init__(self, embedder):super().__init__()self.embedder = embedderemb_dim = self.embedder.embedding_dim#  编码self.encoder = paddlenlp.seq2vec.BoWEncoder(emb_dim)# 计算相似度self.cos_sim_func = nn.CosineSimilarity(axis=-1)def get_cos_sim(self, text_a, text_b):text_a_embedding = self.forward(text_a)text_b_embedding = self.forward(text_b)cos_sim = self.cos_sim_func(text_a_embedding, text_b_embedding)return cos_simdef forward(self, text):# Shape: (batch_size, num_tokens, embedding_dim)embedded_text = self.embedder(text)# Shape: (batch_size, embedding_dim)summed = self.encoder(embedded_text)return summed

2.2 使用 JiebaTokenizer 进行高效的中文文本分词

在处理中文自然语言处理任务时,文本分词是一个非常关键的步骤。本文将详细介绍如何使用 JiebaTokenizer,一个基于 jieba 分词库的自定义分词器类,进行中文文本的分词及其转换为词汇索引。

class JiebaTokenizer():"""Constructs a tokenizer based on `jieba <https://github.com/fxsjy/jieba>`__.It supports :meth:`cut` method to split the text to tokens, and :meth:`encode`method to covert text to token ids.Args:vocab(paddlenlp.data.Vocab): An instance of :class:`paddlenlp.data.Vocab`."""def __init__(self, vocab):super(JiebaTokenizer, self).__init__(vocab)self.tokenizer = jieba.Tokenizer()# initialize tokenizerself.tokenizer.FREQ = {key: 1 for key in self.vocab.token_to_idx.keys()}self.tokenizer.total = len(self.tokenizer.FREQ)self.tokenizer.initialized = Truedef get_tokenizer(self):return self.tokenizerdef cut(self, sentence, cut_all=False, use_hmm=True):"""The method used to cut the text to tokens.Args:sentence(str): The text that needs to be cuted.cut_all(bool, optional): Whether to use the full mode. If True,using full mode that gets all the possible words from thesentence, which is fast but not accurate. If False, usingaccurate mode that attempts to cut the sentence into the mostaccurate segmentations, which is suitable for text analysis.Default: False.use_hmm(bool, optional): Whether to use the HMM model. Default: True.Returns:list[str]: A list of tokens.Example:.. code-block:: pythonfrom paddlenlp.data import Vocab, JiebaTokenizer# The vocab file. The sample file can be downloaded firstly.# wget https://bj.bcebos.com/paddlenlp/data/senta_word_dict.txtvocab_file_path = './senta_word_dict.txt'# Initialize the Vocabvocab = Vocab.load_vocabulary(vocab_file_path,unk_token='[UNK]',pad_token='[PAD]')tokenizer = JiebaTokenizer(vocab)tokens = tokenizer.cut('我爱你中国')print(tokens)# ['我爱你', '中国']"""return self.tokenizer.lcut(sentence, cut_all, use_hmm)def encode(self, sentence, cut_all=False, use_hmm=True):"""The method used to convert the text to ids. It will firstly call:meth:`cut` method to cut the text to tokens. Then, convert tokens toids using `vocab`.Args:sentence(str): The text that needs to be cuted.cut_all(bool, optional): Whether to use the full mode. If True,using full mode that gets all the possible words from thesentence, which is fast but not accurate. If False, usingaccurate mode that attempts to cut the sentence into the mostaccurate segmentations, which is suitable for text analysis.Default: False.use_hmm(bool, optional): Whether to use the HMM model. Default: True.Returns:list[int]: A list of ids.Example:.. code-block:: pythonfrom paddlenlp.data import Vocab, JiebaTokenizer# The vocab file. The sample file can be downloaded firstly.# wget https://bj.bcebos.com/paddlenlp/data/senta_word_dict.txtvocab_file_path = './senta_word_dict.txt'# Initialize the Vocabvocab = Vocab.load_vocabulary(vocab_file_path,unk_token='[UNK]',pad_token='[PAD]')tokenizer = JiebaTokenizer(vocab)ids = tokenizer.encode('我爱你中国')print(ids)# [1170578, 575565]"""words = self.cut(sentence, cut_all, use_hmm)return [get_idx_from_word(word, self.vocab.token_to_idx, self.vocab.unk_token) for word in words]
2.2.1 JiebaTokenizer 类的设计与实现

初始化 jieba.Tokenizer 实例,并设置词频和总词数以匹配提供的词汇表 vocab

class JiebaTokenizer():def __init__(self, vocab):super(JiebaTokenizer, self).__init__(vocab)self.tokenizer = jieba.Tokenizer()# initialize tokenizerself.tokenizer.FREQ = {key: 1 for key in self.vocab.token_to_idx.keys()}self.tokenizer.total = len(self.tokenizer.FREQ)self.tokenizer.initialized = True
2.2.2 分词方法 cut

cut 方法用于将输入的中文句子分割成词汇单元列表。它允许用户选择全模式或精确模式分词,以及是否使用 HMM 模型。这里,lcut 方法来自 jieba 库,根据 cut_alluse_hmm 参数返回最适合的分词结果。

def cut(self, sentence, cut_all=False, use_hmm=True):return self.tokenizer.lcut(sentence, cut_all, use_hmm)
2.2.3 编码方法 encode

encode 方法中,我们首先使用 cut 方法对句子进行分词,然后将分词结果转换为词汇索引。

def encode(self, sentence, cut_all=False, use_hmm=True):words = self.cut(sentence, cut_all, use_hmm)return [self.vocab.token_to_idx.get(word, self.vocab.unk_token) for word in words]

展示如何将分词结果映射到它们对应的索引值。若词汇不存在于词汇表中,则使用未知词标记 unk_tokenJiebaTokenizer 提供了一个强大且灵活的方式来处理中文文本,非常适合用于自然语言处理中的文本预处理。通过这个类,开发者可以轻松地集成 jieba 的分词功能到自己的 NLP 项目中,提高文本处理的效率和精度。

计算得到句子之间的相似度

    text_pairs = {}with open("data/text_pair.txt", "r", encoding="utf8") as f:for line in f:text_a, text_b = line.strip().split("\t")if text_a not in text_pairs:text_pairs[text_a] = []text_pairs[text_a].append(text_b)for text_a, text_b_list in text_pairs.items():text_a_ids = paddle.to_tensor([tokenizer.text_to_ids(text_a)])for text_b in text_b_list:text_b_ids = paddle.to_tensor([tokenizer.text_to_ids(text_b)])print("text_a: {}".format(text_a))print("text_b: {}".format(text_b))print("cosine_sim: {}".format(model.get_cos_sim(text_a_ids, text_b_ids).numpy()[0]))# print()

参考百度飞桨链接:PaddleNLP词向量应用展示

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/4346.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ESP32-S3的MQTT实战

昨天&#xff0c;我们讲了socket通信&#xff0c;当服务器和客户端建立起连接时&#xff0c;就可以互相通信了。在互联网应用大多使用WebSocket接口来传输数据。而在物联网的应用中&#xff0c;常常出现这种情况&#xff1a;海量的传感器&#xff0c;需要时刻保持在线&#xff…

微信小程序[黑马笔记]

简介 常用组件 视图组件 <!--pages/list/list.wxml--><scroll-view class"container1" scroll-y><view>A</view><view>B</view><view>A</view></scroll-view><!--pages/list2/list.wxml--><swiper …

❤mac使用Idea工具

❤mac使用Idea工具 1、安装 直接跳过&#xff0c;文章有 &#xff08;点击跳转&#xff09; 给自己的mac系统上安装java环境 2、使用 快捷键 Command , 系统首选项 设置Idea连接数据库 打开右侧的database&#xff08;或菜单里&#xff09;连接数据库&#xff0c;根据提…

Ubuntu中的 Everything 搜索软件 ==> fsearch

本文所使用的 Ubuntu 系统版本是 Ubuntu 22.04 ! 在 Windows 中&#xff0c;我经常使用 Everything 来进行文件搜索&#xff0c;搜索效率比 Windows 自带的高出千百倍。 那么在 Ubuntu 系统中&#xff0c;有没有类似的软件呢&#xff1f;那必须有&#xff0c;它就是 FSearch 。…

安防监控/智能分析EasyCVR视频汇聚平台海康/大华/宇视摄像头国标语音GB28181语音对讲配置流程

一、背景分析 近年来&#xff0c;国内视频监控应用发展迅猛&#xff0c;系统接入规模不断扩大&#xff0c;涌现了大量平台提供商&#xff0c;平台提供商的接入协议各不相同&#xff0c;终端制造商需要给每款终端维护提供各种不同平台的软件版本&#xff0c;造成了极大的资源浪…

libVLC 制作一款精美的播放器

1.简介 本文将简单介绍使用libVLC制作一款精美的播放器。 开发环境:Visual Studio + Qt插件。 Qt版本:Qt5.9。 libVLC版本:3.0.20。 以下是运行界面效果图:截取其中几张。 右键菜单,功能还是比较齐全。 2.ui界面构成 接下来简单介绍一下ui界面构成。 主界面由播放树…

Mac下使用homebrew管理多版本mysql同时启动

Mac下使用homebrew管理多版本mysql同时启动 思路 给每个版本分配不同的数据目录和配置文件即可 本文尝试了使用 brew 安装管理多个MySQL版本&#xff0c;同时运行、直接切换 安装 如果已有数据文件请自行备份以及使用 安装 mysql 5.7 brew install mysql5.7在 /opt/home…

开发 Chrome 浏览器插件入门

前言 简介 Chrome 插件是扩展 Chrome 浏览器的功能的软件程序。它们可以执行各种任务&#xff0c;例如阻止广告、增强隐私、添加新功能等等。 要开始编写 Chrome 插件&#xff0c;你需要掌握以下&#xff1a; 1.JavaScript语言 2.html 3.css 4.会使用chrome扩展开发手册…

Git系列:Git Branch 用法总结

&#x1f49d;&#x1f49d;&#x1f49d;欢迎莅临我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:「stormsha的主页」…

Docker数据管理与Dockerfile镜像创建

前言 在容器化环境中&#xff0c;如何有效地管理和持久化数据成为了开发人员和运维团队面临的挑战之一&#xff1b;另一方面&#xff0c;镜像的创建是构建容器化应用的基础。优化的镜像设计可以提高部署效率和应用性能&#xff0c;减少资源消耗和运行成本。本文将介绍 Docker …

纯血鸿蒙APP实战开发——预渲染实现Web页面瞬开效果

介绍 为了便于大家在使用本案例集时能够更详细的了解各个案例&#xff0c;本案例基于Web预渲染实现了案例介绍功能&#xff0c;即应用右下角的问号icon。 效果图预览 使用说明 因为直接加载的线上README&#xff0c;因此本功能需联网使用点击icon&#xff0c;即会弹出对应案…

后端端口也可以直接在浏览器访问

比如在浏览器输入http://localhost:8078/hello/helloword访问的是后端的 RestController RequestMapping("/hello") public class HelloWord {RequestMapping("/helloword")public String helloWord(){return "hello word";} }浏览器将会返回

论文阅读之MMSD2.0: Towards a Reliable Multi-modal Sarcasm Detection System

文章目录 论文地址主要内容主要贡献模型图技术细节数据集改进多视图CLIP框架文本视图图像视图图像-文本交互视图 实验结果 论文地址 https://arxiv.org/pdf/2307.07135 主要内容 这篇文章介绍了一个名为MMSD2.0的多模态讽刺检测系统的构建&#xff0c;旨在提高现有讽刺检测系…

B+tree - B+树深度解析+C语言实现+opencv绘图助解

Btree - B树深度解析C语言实现opencv绘图助解 1. 概述2. Btree介绍3. Btree算法实现3.1 插入分裂 3.2 删除向右借位&#xff08;左旋&#xff09;向左借位&#xff08;右旋&#xff09;合并 3.3 查询和遍历3.3.1 查询3.3.2 遍历 3.4 优化优化1(匀key)优化2(升级key)优化3(拓展兄…

vue3 vite 路由去中心化(modules文件夹自动导入router)

通过路由去中心化可实现多人写作开发&#xff0c;不怕文件不停修改导致的冲突&#xff0c;modules中的文件可自动导入到index.js中 // 自动导入模块 const files import.meta.globEager(./modules/**.js); const modules {} for (const key in files) {modules[key.replace…

Android 开发工具使用

c调试 在NDK调试的时候&#xff0c;如果找不到 符号的话&#xff0c;我们可以在调试配置中添加符号地址的全路径一直到根目录&#xff1a;&#xff0c;xxx/armeabi-v7a&#xff1a; You must point the symbol search paths at the obj/local/ directory. This is also not a …

【Vue】如何使用Webpack实现打包操作

一、Webpack介绍 Webpack最主要的作用就是打包操作&#xff0c;由两个核心部分构成分别是“出口”与“入口”。wbepack是现在比较热门的打包工具了&#xff0c;它可以将许多松散耦合的模块按照依赖和规则打包成符合生产环境部署的前端资源。说的直白一点&#xff0c;通过webpac…

redission原理笔记

加锁成功的线程&#xff0c;将UUID和线程id和key绑定&#xff0c; 加锁成功后&#xff0c;内部有一个看门狗机制&#xff0c;每隔十秒看下当前线程是否还持有锁&#xff0c;延长生存时间。 没有获取锁的就一直自旋等待&#xff0c;直到超时。 如果redis是主从同步的&#xff0…

自动驾驶新书“五一”节马上上市了

我和杨子江教授合写的《自动驾驶系统开发》终于在清华大学出版社三校稿之后即将在五一节后出版。 清华大学汽车学院的李克强教授和工程院院士撰写了序言。 该书得到了唯一华人图灵奖获得者姚期智院士、西安交大管晓宏教授和科学院院士以及杨强教授和院士等的推荐&#xff0c;…

不使用加减运算符实现整数加和减

文章目录 进位 进位 加粗 最近想出了不使用运算符实现加与减 首先按位与找出的是需不需要进位 按位与是两边同时为1,则为1,那么如果两边同时为1的话,是不是就该进位?所以我们用按位与来判断是否需要进位 然后再按位异或找出不同的位数 按位异或是两边不相等,也就是1 和 0的时…