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

news/2024/5/22 2:57:44

词向量介绍

  • 词向量(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.mrgr.cn/p/03377650

相关文章

品牌百度百科词条需要什么资料?

品牌百度百科词条是一个品牌的数字化名片&#xff0c;更是品牌历史、文化、实力的全面展现。 作为一个相当拿得出手的镀金名片&#xff0c;品牌百度百科词条创建需要什么资料&#xff0c;今天伯乐网络传媒就来给大家讲解一下。 一、品牌基本信息&#xff1a;品牌身份的明确 品…

树莓派5用docker运行Ollama3

书接上回&#xff0c;树莓派5使用1panel安装 Ollama 点击终端就可以进入容器 输入以下代码 ollama run llama3Llama3 是市场推崇的版本。您的 树莓派5上必须至少有 4.7GB 的可用空间&#xff0c;因此用树莓派玩机器学习就必须配置大容量的固态硬盘。用1panel部署网络下载速度…

prompt提示词:AI英语词典优化版Pro,让AI教你学英语,通过AI实现一个网易有道英语词典

目录 一、前言二、效果对比三、优化《AI英语词典》提示词四、其他获奖作品链接 一、前言 不可思议&#xff01;我的AI有道英语字典助手竟然与百度千帆AI应用创意挑战赛K12教育主题赛榜首作品差之毫厘 &#xff0c;真的是高手都是惺惺相惜的&#xff0c;哈哈&#xff0c;自恋一…

C++重写

数组 DiscoveredTileIndexed 和 DiscoveredTileSortingCosts 这两个数组是用来存储遍历的方格的,DiscoveredTileSortingCosts存储的是每个方格的消耗,DiscoveredTileIndexed存储的是每个方格的位置即(x,y)。 DiscoveredTileSortingCosts中的消耗和DiscoveredTileIndexed位置是…

音视频入门基础:像素格式专题(1)——RGB简介

一、像素格式简介 像素格式&#xff08;pixel format&#xff09;指像素色彩按分量的大小和排列。这种格式以每个像素所使用的总位数以及用于存储像素色彩的红、绿、蓝和 alpha 分量的位数指定。在音视频领域&#xff0c;常用的像素格式包括RGB格式和YUV格式&#xff0c;本文…

光伏管理系统:降本增效解决方案。

现在是光伏发展的重要节点&#xff0c;如何在众多同行中脱颖而出并且有效的达到降低成本、提高效率也是很多企业都在考虑的问题&#xff0c;鹧鸪云的团队研发出了光伏管理系统&#xff0c;通过更高效、更智能、更全面的管理方式来帮助企业实现降本增效的转型&#xff0c;小编带…

神经网络反向传播算法

今天我们来看一下神经网络中的反向传播算法&#xff0c;之前介绍了梯度下降与正向传播~ 神经网络的反向传播 专栏&#xff1a;&#x1f48e;实战PyTorch&#x1f48e; 反向传播算法&#xff08;Back Propagation&#xff0c;简称BP&#xff09;是一种用于训练神经网络的算…

WebAuthn 无密码身份认证

文章目录 WebAuthn简介工作原理组成部分架构实现注册认证应用场景案例演示 WebAuthn简介 WebAuthn&#xff0c;全称 Web Authentication&#xff0c;是由 FIDO 联盟&#xff08;Fast IDentity Online Alliance&#xff09;和 W3C&#xff08;World Wide Web Consortium&#x…

多线程事务怎么回滚

1、背景介绍 1&#xff0c;最近有一个大数据量插入的操作入库的业务场景&#xff0c;需要先做一些其他修改操作&#xff0c;然后在执行插入操作&#xff0c;由于插入数据可能会很多&#xff0c;用到多线程去拆分数据并行处理来提高响应时间&#xff0c;如果有一个线程执行失败…

【网络知识系列】-- 换个角度理解计算机网络

换个角度理解计算机网络,搭建计网知识框架 所谓换个角度,就是从三层物理设备(物理层、数据链路层、网络层)开始,串联起整个网络的工作原理 可能有些小伙伴看见物理设备天生就犯困,反手就准备关闭文章,且慢!本文只是简单的介绍这几个设备的功能,并不会涉及复杂的底层硬…

C#学习笔记-字段、属性、索引器

字段字段表示与对象或者类型(类或结构体)关联的变量(成员变量),为对象或类型存储数据。与对象关联的字段称为“实例字段”,隶属于某个对象。与类型关联的字段称为“静态字段”,表示某一个类型当前的状态。静态字段使用 static 关键字修饰。字段在没有显示初始化的情况下…

力扣-203. 移除链表元素

1.题目 题目地址(203. 移除链表元素 - 力扣(LeetCode)) https://leetcode.cn/problems/remove-linked-list-elements/ 题目描述 给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。示例 1:输入:head = [1,2…

SpringCloud学习笔记(二)Ribbon负载均衡、Nacos注册中心、Nacos与Eureka的区别

文章目录 4 Ribbon负载均衡4.1 负载均衡原理4.2 源码解读4.3 负载均衡策略4.3.1 内置的负载均衡策略4.3.2 自定义负载均衡策略4.3.2.1 方式一&#xff1a;定义IRule4.3.2.2 方式二&#xff1a;配置文件 4.4 饥饿加载 5 Nacos注册中心5.1 认识和安装Nacos5.2 服务注册到Nacos5.3…

【云原生】Docker 实践(三):使用 Dockerfile 文件构建镜像

Docker 实践&#xff08;三&#xff09;&#xff1a;使用 Dockerfile 文件构建镜像 1.使用 Dockerfile 文件构建镜像2.Dockerfile 文件详解 1.使用 Dockerfile 文件构建镜像 Dockerfile 是一个文本文件&#xff0c;其中包含了一条条的指令&#xff0c;每一条指令都用于构建镜像…

网络接收全流程

网卡简介 网卡是一块通信硬件。属于数据链路层。用户可以通过电缆或无线相互连接。每一个网卡都有一个独一无二的MAC地址(48位),它被写在卡上的一块ROM中。IEEE负责为网卡销售商分配唯一的MAC地址。 可以在终端运行sudo lshw -C network来查看网卡型号 可以在/lib/modules/$(u…

中科院突破:TalkingGaussian技术实现3D人脸动态无失真,高效同步嘴唇运动!

DeepVisionary 每日深度学习前沿科技推送&顶会论文分享&#xff0c;与你一起了解前沿深度学习信息&#xff01; 引言&#xff1a;探索高质量3D对话头像的新方法 在数字媒体和虚拟互动领域&#xff0c;高质量的3D对话头像技术正变得日益重要。这种技术能够在虚拟现实、电影…

Linux操作系统·进程管理

一、什么是进程 1.作业和进程的概念 Linux是一个多用户多任务的操作系统。多用户是指多个用户可以在同一时间使用计算机系统&#xff1b;多任务是指Linux可以同时执行几个任务&#xff0c;它可以在还未执行完一个任务时又执行另一项任务。为了完成这些任务&#xff0c;系统上…

《痞子衡嵌入式半月刊》 第 99 期

痞子衡嵌入式半月刊: 第 99 期这里分享嵌入式领域有用有趣的项目/工具以及一些热点新闻,农历年分二十四节气,希望在每个交节之日准时发布一期。 本期刊是开源项目(GitHub: JayHeng/pzh-mcu-bi-weekly),欢迎提交 issue,投稿或推荐你知道的嵌入式那些事儿。 上期回顾 :《…

Codeforces Round 942 Div.2 题解

ds 这么聪明的。蹭个热度,挽救一下 cnblogs 蒸蒸日上的阅读量。Q: 你是手速狗吗? A: 我觉得我是。2A 因为选的 \(w\) 一定可以让它合法,一次操作可以看作 \(a\) 数组向右平移一位。枚举操作次数后暴力判断即可。 #include <bits/stdc++.h>void work() {int n;std::cin…

linux下调试串口设备

USB转串口常用CH34x芯片,该芯片有linux下的驱动。 在默认情况下,大部分linux发行版都包含了CH34x的驱动,唯一缺点就是版本比较久。 可以先插上开发板, 一般是挂载到/dev/ttyCH341USB0文件下,如果该文件不存在,有两种可能,一种是驱动版本太久,可以下载官方的驱动文件,然…