Embedding理解与代码实现

article/2025/10/20 15:45:14

Embedding 字面理解是 “嵌入”,实质是一种映射,从语义空间到向量空间的映射,同时尽可能在向量空间保持原样本在语义空间的关系,如语义接近的两个词汇在向量空间中的位置也比较接近。

下面以一个基于Keras的简单的文本情感分类问题为例解释Embedding的训练过程:

首先,导入Keras的相关库

from keras.layers import Dense, Flatten, Input
from keras.layers.embeddings import Embedding
from keras.models import Model
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import one_hot
import numpy as np

给出文本内容和label

# define documents
docs = ['Well done!','Good work','Great effort','nice work','Excellent!','Weak','Poor effort!','not good','poor work','Could have done better.']
# define class labels
labels = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]

然后将文本编码成数字格式并padding到相同长度

# integer encode the documents
vocab_size = 50
encoded_docs = [one_hot(d, vocab_size) for d in docs]   
print(encoded_docs)# pad documents to a max length of 4 words
max_length = 4
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post')
print(padded_docs)

上面两个print输出如下,每次运行得到的数字可能会不一样,但同一个单词对应相同的数字。上述one_hot编码映射到[1,n],不包括0,n为上述的vocab_size,为估计的词汇表大小。然后padding到最大的词汇长度,用0向后填充,这也是为什么前面one-hot不会映射到0的原因。

[[41, 13], [14, 5], [11, 19], [30, 5], [47], [16], [37, 19], [26, 14], [37, 5], [38, 40, 13, 19], [37], [14]][[41 13  0  0][14  5  0  0][11 19  0  0][30  5  0  0][47  0  0  0][16  0  0  0][37 19  0  0][26 14  0  0][37  5  0  0][38 40 13 19][37  0  0  0][14  0  0  0]]

模型的定义

# define the model
input = Input(shape=(4, ))
x = Embedding(vocab_size, 8, input_length=max_length)(input)    #这一步对应的参数量为50*8
x = Flatten()(x)
x = Dense(1, activation='sigmoid')(x)
model = Model(inputs=input, outputs=x)
# compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
# summarize the model
print(model.summary())	#输出模型结构

输出的模型结构如下所示:

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 4)                 0         
_________________________________________________________________
embedding_1 (Embedding)      (None, 4, 8)              400       
_________________________________________________________________
flatten_1 (Flatten)          (None, 32)                0         
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 33        
=================================================================

这里先介绍一下Keras中的Embedding函数,详细见z官方文档:Embedding

keras.layers.Embedding(input_dim, output_dim, input_length)
  • input_dim:这是文本数据中词汇的取值可能数。例如,如果您的数据是整数编码为0-9之间的值,那么词汇的大小就是10个单词;
  • output_dim:这是嵌入单词的向量空间的大小。它为每个单词定义了这个层的输出向量的大小。例如,它可能是32或100甚至更大,可以视为具体问题的超参数;
  • input_length:这是输入序列的长度,就像您为Keras模型的任何输入层所定义的一样,也就是一次输入带有的词汇个数。例如,如果您的所有输入文档都由1000个字组成,那么input_length就是1000。

再看一下keras中embeddings的源码,其构建函数如下:

    def build(self, input_shape):self.embeddings = self.add_weight(shape=(self.input_dim, self.output_dim),initializer=self.embeddings_initializer,name='embeddings',regularizer=self.embeddings_regularizer,constraint=self.embeddings_constraint,dtype=self.dtype)self.built = True

可以看到它的参数shape为(self.input_dim, self.output_dim),在上述例子中即(50,8)

上面输出的模型结构中Embedding层的参数为400,它实质就是50*8得到的,这是一个关键要理解的信息。

我们知道one-hot 是无法考虑语义间的相互关系的,但embedding向量的训练是要借助one-hot的。上面的one-hot把每一个单词映射成一个整数,但实际上这个整数就表示了50维向量中 1 所在的索引位置,用整数显示是为了更好理解和表示,而实际在网络中,它的形式可以理解为如下图(下面相当于one-hot向量为5维,输出embedding向量为3维)

右边的神经元为one-hot输入,左边为得到的embedding表示,图中1所对应的红线权重就是该单词对应的词向量,这一层神经元只能作为第一层嵌入,是没有偏置和激活函数的,它也可以被理解为如下的一个矩阵相乘,输出就是该单词的词向量。然后词向量再输入到下一层。这一层总的参数量就是这些权重,也是下面中间的矩阵。

一个词组中有多个单词,如上面例子中有四个,那就分别经过这一层得到四个词向量,然后Flatten 到一层,再后接全连接层进行分类。因此,在这个模型中,embedding向量和分类模型是同时训练的,当然也可以用他人在大预料库中已经训练好的向量来直接训练分类。

上述例子的完整代码如下:

from keras.layers import Dense, Flatten, Input
from keras.layers.embeddings import Embedding
from keras.models import Model
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import one_hot
import numpy as np
# define documents
docs = ['Well done!','Good work','Great effort','nice work','Excellent!','Weak','Poor effort!','not good','poor work','Could have done better.']# define class labels
labels = np.array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0])
# integer encode the documents
vocab_size = 50
encoded_docs = [one_hot(d, vocab_size) for d in docs]   #one_hot编码到[1,n],不包括0
print(encoded_docs)# pad documents to a max length of 4 words
max_length = 4
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post')
print(padded_docs)# define the model
input = Input(shape=(4, ))
x = Embedding(vocab_size, 8, input_length=max_length)(input)    #这一步对应的参数量为50*8
x = Flatten()(x)
x = Dense(1, activation='sigmoid')(x)
model = Model(inputs=input, outputs=x)
# compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
# summarize the model
print(model.summary())# fit the model
model.fit(padded_docs, labels, epochs=100, verbose=0)
# evaluate the model
loss, accuracy = model.evaluate(padded_docs, labels, verbose=0)
loss_test, accuracy_test = model.evaluate(padded_docs, labels, verbose=0)
print('Accuracy: %f' % (accuracy * 100))
# test the model
test = one_hot('good',50)
padded_test = pad_sequences([test], maxlen=max_length, padding='post')
print(model.predict(padded_test)) 

图片参考自:https://blog.csdn.net/laolu1573/article/details/77170407


http://chatgpt.dhexx.cn/article/LENxvZyh.shtml

相关文章

深度学习中Embedding层有什么用?

2019年03月24日15:23:32更新: 由于CSDN图片经常显示不出来,本文最新链接请点击:https://fuhailin.github.io/Embedding/ 博主所有博客写作平台已迁移至:https://fuhailin.github.io/ ,欢迎收藏关注。 这篇博客翻译自国…

pytorch nn.Embedding的用法和理解

(2021.05.26补充)nn.Embedding.from_pretrained()的使用: >>> # FloatTensor containing pretrained weights >>> weight torch.FloatTensor([[1, 2.3, 3], [4, 5.1, 6.3]]) >>> embedding nn.Embedding.from…

EMBEDDING层作用

embedding层作用:①降维②对低维的数据进行升维时,可能把一些其他特征给放大了,或者把笼统的特征给分开了。 Embedding其实就是一个映射,从原先所属的空间映射到新的多维空间中,也就是把原先所在空间嵌入到一个新的空…

彻底理解embedding

本文转载自https://blog.csdn.net/weixin_42078618/article/details/84553940,版权问题请联系博主删除 首先,我们有一个one-hot编码的概念。 假设,我们中文,一共只有10个字。。。只是假设啊,那么我们用0-9就可以表示…

深度学习中的embedding

整理翻译自google developer的机器学习入门课程,介绍了embedding的应用方式和如何计算embedding,后面还配有通过tensorflow DNN训练embedding练习加深理解。 分类输入数据(Categorical Input Data) 分类数据是指表示来自有限选择集的一个或多个离散项的…

【文本分类】深入理解embedding层的模型、结构与文本表示

[1] 名词理解 embedding层:嵌入层,神经网络结构中的一层,由embedding_size个神经元组成,[可调整的模型参数]。是input输入层的输出。 词嵌入:也就是word embedding…根据维基百科,被定义为自然语言处理NLP中…

用万字长文聊一聊 Embedding 技术

作者:qfan,腾讯 WXG 应用研究员 随着深度学习在工业届不断火热,Embedding 技术便作为“基本操作”广泛应用于推荐、广告、搜索等互联网核心领域中。Embedding 作为深度学习的热门研究方向,经历了从序列样本、图样本、再到异构的多…

Embedding技术

1、Embedding 是什么 Embedding是用一个低维稠密的向量来“表示”一个对象(这里的对象泛指一切可推荐的事物,比如商品、电影、音乐、新闻等),同时表示一词意味着Embedding能够表达相应对象的某些特征,同时向量之间的距…

什么是embedding?

本文转自:https://www.jianshu.com/p/6c977a9a53de    简单来说,embedding就是用一个低维的向量表示一个物体,可以是一个词,或是一个商品,或是一个电影等等。这个embedding向量的性质是能使距离相近的向量对应的物体…

Pairwise-ranking loss代码实现对比

Multi-label classification中Pairwise-ranking loss代码 定义 在多标签分类任务中,Pairwise-ranking loss中我们希望正标记的得分都比负标记的得分高,所以采用以下的形式作为损失函数。其中 c c_ c​是正标记, c − c_{-} c−​是负标记。…

【论文笔记】API-Net:Learning Attentive Pairwise Interaction for Fine-Grained Classification

API-Net 简介创新点mutual vector learning(互向量学习)gate vector generation(门向量生成器)pairwise interaction(成对交互) 队构造(Pair Construction)实验结果总结 简介 2020年…

白话点云dgcnn中的pairwise_distance

点云DGCNN中对于代码中pairwise_distance的分析与理解 2021年5月7日:已经勘误,请各位大佬不惜赐教。 一点一点读,相信我,我能讲清楚。 这个是本篇文章所要讨论的代码段 总体上把握,这个代码计算出了输入点云每对点之…

推荐系统[四]:精排-详解排序算法LTR (Learning to Rank): poitwise, pairwise, listwise相关评价指标,超详细知识指南。

搜索推荐系统专栏简介:搜索推荐全流程讲解(召回粗排精排重排混排)、系统架构、常见问题、算法项目实战总结、技术细节以及项目实战(含码源) 专栏详细介绍:搜索推荐系统专栏简介:搜索推荐全流程讲解(召回粗排精排重排混排)、系统架构、常见问题、算法项目实战总结、技术…

【torch】torch.pairwise_distance分析

every blog every motto: You can do more than you think. https://blog.csdn.net/weixin_39190382?typeblog 0. 前言 记录torch.pairwise_distance 1. 一维 1.1 元素个数相同 1.1.1 元素个数为1 生成代码: t torch.randn(1) f torch.randn(1)计算代码,下…

pairwise损失_triplet损失_提升精排模型的trick

01标签 import torch import torch.nn as nn# 输入x是一个二维张量,每一行表示一个样本的分数,每一列表示一个特征或维度 x torch.tensor([[0.5, 0.7], [0.9, 0.8], [0.6, 0.4], [0.3, 0.6], [0.8, 0.7], [0.4, 0.5]])# 标签y是一个一维张量&#xff0c…

LTR (Learning to Rank): 排序算法 poitwise, pairwise, listwise常见方案总结

目录 1 Learing to Rank介绍2 The Pointwise Approach3 The Pairwise Approach3.1 RankNet 4 The Listwise Approach4.1 直接优化评测指标4.1.1 LambdaRank4.1.2 LambdaMART 4.2 定义Listwise损失函数4.2.1 ListNet4.2.2 ListMLE 5 排序评估指标5.1 Mean Reciprocal Rank (MRR)…

【论文精读】Pairwise learning for medical image segmentation

Published in: Medical Image Analysis 2020 论文:https://www.sciencedirect.com/science/article/abs/pii/S1361841520302401 代码:https://github.com/renzhenwang/pairwise_segmentation 目录 Published in: Medical Image Analysis 2020 摘要 一…

pairwise相似度计算

做了一个比赛,其中为了更好的构建负样本,需要计算不同句子之间的相似性,句子大概有100w,句子向量是300维,中间踩了很多坑,记录一下。 暴力计算 最简单的idea是预分配一个100w x 100w的矩阵,一…

如何计算 Pairwise correlations

Pairwise Correlation的定义是啥?配对相关性?和pearson correlations有什么区别? Pairwise Correlation顾名思义,用来计算两个变量间的相关性,而pearson correlations只是计算相关性的一种方法罢了。 1、pearson相关系…

再谈排序算法的pairwise,pointwise,listwise

NewBeeNLP干货 作者:DOTA 大家好,这里是 NewBeeNLP。 最近因为工作上的一些调整,好久更新文章和个人的一些经验总结了,下午恰好有时间,看了看各渠道的一些问题和讨论,看到一个熟悉的问题,在这…