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

词向量介绍

  • 词向量(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 = embedder
        emb_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_sim

    def 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 tokenizer
        self.tokenizer.FREQ = {key: 1 for key in self.vocab.token_to_idx.keys()}
        self.tokenizer.total = len(self.tokenizer.FREQ)
        self.tokenizer.initialized = True
    def get_tokenizer(self):
        return self.tokenizer

    def 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 the
                sentence, which is fast but not accurate. If False, using
                accurate mode that attempts to cut the sentence into the most
                accurate 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:: python

                from 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.txt
                vocab_file_path = './senta_word_dict.txt'
                # Initialize the Vocab
                vocab = 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 to
        ids 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 the
                sentence, which is fast but not accurate. If False, using
                accurate mode that attempts to cut the sentence into the most
                accurate 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:: python

                from 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.txt
                vocab_file_path = './senta_word_dict.txt'
                # Initialize the Vocab
                vocab = 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 tokenizer
        self.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.mfbz.cn/a/586942.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

pytorch中创建maskrcnn模型

0.模型输入/输出参数参见 链接: pytorch的mask-rcnn的模型参数解释 核心代码 GeneralizedRCNN(这里以mask-rcnn来解释说明) # 通过输入图像获取fpn特征图,注意这里的backbone不是直接的resnet,而是fpn化后的 features self.backbone(images.tensors) # 由于是mask-rcnn,故而…

如何快速搭建nginx服务

华子目录 nginx简介概念特点nginx框架nginx关键工作机制 nginx正向代理功能nginx反向代理功能nginx反向代理的工作流程代理本质 nginx负载均衡部署nginx常用命令systemctl系列nginx自带命令 nginx配置文件主配置文件/etc/nginx/nginx.conf内容结构模块分析配置分析注意示例 ngi…

Android创建快捷方式到桌面

效果图 参考 https://blog.51cto.com/u_16175498/8811197https://blog.51cto.com/u_16175498/8811197 权限 <uses-permission android:name"com.android.launcher.permission.INSTALL_SHORTCUT" /> 实现 if (Build.VERSION.SDK_INT > Build.VERSION_C…

【已解决】Python Selenium chromedriver Pycharm闪退的问题

概要 根据不同的业务场景需求&#xff0c;有时我们难免会使用程序来打开浏览器进行访问。本文在pycharm中使用selenium打开chromedriver出现闪退问题&#xff0c;根据不断尝试&#xff0c;最终找到的问题根本是版本问题。 代码如下 # (1) 导入selenium from selenium import …

C++ stack、queue以及deque

1、stack和queue常用接口 严格来说栈和队列的实现是容器适配器 1、常用接口&#xff1a; 栈&#xff1a;top、push、pop、size、emptystack - C Reference (cplusplus.com) 队列&#xff1a;top、push、pop、swap、size、emptyqueue - C Reference (cplusplus.com) 2、deque&a…

Android手势识别面试问题及回答

问题 1: 如何在Android中实现基本的手势识别&#xff1f; 答案: 在Android中&#xff0c;可以通过使用GestureDetector类来实现基本的手势识别。首先需要创建一个GestureDetector的实例&#xff0c;并实现GestureDetector.OnGestureListener接口来响应各种手势事件&#xff0c…

ubuntu安装mysql时候修改root密码

前情&#xff1a; 使用set password for rootlocalhost ‘passwd’&#xff1b; set password for ‘root’‘localhost’‘passwd’&#xff1b; update user set passwordpassword(‘passwd’) where user‘root’ and host ‘localhost’; flush privileges; 以上方法均报…

定制开发AI智能名片商城小程序:玩转积分制度的成功案例

在数字化浪潮席卷而来的今天&#xff0c;企业营销方式不断创新&#xff0c;力求在众多竞争对手中脱颖而出。其中&#xff0c;积分制度以其直观、有效的特点&#xff0c;成为了众多企业的营销利器。某时尚品牌“潮流前线”便是其中的佼佼者。他们通过定制一款AI智能名片商城小程…

德国著名自动化公司Festo设计了一款仿生蜜蜂,仅重34g,支持多只蜜蜂编队飞行!...

德国著名的气动元件研发及自动化解决方案供应商Festo公司近日展示了一款仿生蜜蜂&#xff08;BionicBee&#xff09;&#xff0c;重量只有34g&#xff0c;却完全可以实现自主飞行&#xff0c;还支持多只相同的蜜蜂机器人编队飞行。 BionicBee 重约 34 克&#xff0c;长 22 厘米…

二叉树的前序,中序,后序遍历

二叉树可以分为左子树&#xff0c;右子树和根节点。同时左子树和右子树又可以分为新的左子树和右子树加上新的根节点&#xff0c;以此类推。 二叉树的前序&#xff0c;中序&#xff0c;后序遍历也叫前根遍历&#xff0c;中根遍历&#xff0c;后根遍历或者前序遍历&#xff0c;…

【Vue 2.x】学习vue之三路由

文章目录 Vue三路由第十章1、vue中的路由vue的应用分为a、多页面应用b、单页面应用 2、路由的基本应用1、基础2、使用3、加载 3、vue组件的分类1、普通组件2、路由组件 4、路由的嵌套5、路由传递Query参数1、拼接参数传递2、路由传递对象 6、简化路由1、命名路由 7、parms传递参…

控制台主机不能运行,切换终端实现RPG运行

鄙人转载&#xff0c;主要是移植过程中使用小熊猫C2.25.1 过程中&#xff0c;字符集不同&#xff0c;导致某些空格 从bilibili专栏粘贴导致出现符号不匹配&#xff0c;但是编辑器不能替换 用原来的devc 5.11 发现问题&#xff0c;读出额外的英文&#xff1f; 使用文件替换&…

C语言贪吃蛇项目

今天给大家带来一款简单的贪吃蛇游戏&#xff0c;一起随我来看看吧 游戏效果&#xff1a; 实现基本的功能&#xff1a; • 贪吃蛇地图绘制 • 蛇吃⻝物的功能&#xff1a;&#xff08;上、下、左、右⽅向键控制蛇的动作&#xff09; • 蛇撞墙死亡 • 蛇撞⾃⾝死亡 • 计算得分…

5.C++动态内存管理(超全)

目录 1 .C/C 内存分布 2. C语言中动态内存管理方式&#xff1a;malloc/calloc/realloc/free 3. C内存管理方式 3.1 new/delete操作内置类型 3.2 new和delete操作自定义类型 3.3 operator new函数 3.4 定位new表达式(placement-new) &#xff08;了解&#xff09; 4. 常…

【ARMv8/v9 系统寄存 3 -- system counter CNTPCT_EL0】

文章目录 ARMv8/v9 system countersystem counter读取函数实现 ARMv8/v9 system counter 所有使用Arm处理器的系统中都会包含一个标准化的通用定时器&#xff08;Generic Timer&#xff09;框架。这个通用定时器系统提供了一个系统计数器&#xff08;System Counter&#xff0…

ps科研常用操作,制作模式图 扣取想要的内容元素photoshop

复制想要copy的图片&#xff0c; 打开ps---file-----new &#xff0c;ctrolv粘贴图片进入ps 选择魔棒工具&#xff0c;点击想要去除的白色区域 然后&#xff0c;cotrol shift i&#xff0c;反选&#xff0c; ctrol shiftj复制&#xff0c;复制成功之后&#xff0c;一定要改…

UnityWebGL获取话筒实时数据

看了木子李大佬的数字人https://digital.lkz.fit/之后&#xff0c;我也想搞一个&#xff0c;于是开始研究起来&#xff0c;先从WebGL录音开始&#xff0c;一共试了三个插件&#xff0c;个个都有问题…… 1、UnityWebGLMicrophone 用起来没啥问题&#xff0c;但是只能录音&#…

大型企业总分支多区域数据传输,效率为先还是安全为先?

大型企业为了业务拓展需要&#xff0c;会在全国乃至全球各地设立分公司和办事机构&#xff0c;以便更好地处理当地事务&#xff0c;并进行市场的开拓和客户维护&#xff0c;此时&#xff0c;企业内部就衍生出了新的业务需求&#xff0c;即多区域数据传输。 多区域很难准确定义&…

【大语言模型LLM】-基于ChatGPT搭建客服助手(1)

&#x1f525;博客主页&#xff1a;西瓜WiFi &#x1f3a5;系列专栏&#xff1a;《大语言模型》 很多非常有趣的模型&#xff0c;值得收藏&#xff0c;满足大家的收集癖&#xff01; 如果觉得有用&#xff0c;请三连&#x1f44d;⭐❤️&#xff0c;谢谢&#xff01; 长期不…

2024年五一杯高校数学建模竞赛(A题)|钢板切割问题 | 建模解析,小鹿学长带队指引全代码文章与思路

我是鹿鹿学长&#xff0c;就读于上海交通大学&#xff0c;截至目前已经帮200人完成了建模与思路的构建的处理了&#xff5e; 本篇文章是鹿鹿学长经过深度思考&#xff0c;独辟蹊径&#xff0c;通过路径优化解决钢板切割问题。结合贪心算法&#xff0c;Floyd-Warshall等多元算法…
最新文章