词向量:编码词汇级别的信息

url:http://pytorch.org/tutorials/beginner/nlp/word_embeddings_tutorial.html?highlight=lookup

词嵌入

词嵌入是稠密向量,每个都代表了一个单词表里面的一个单词。NLP中每个Feature都是单词,但是怎么在电脑中表示单词呢??

ascii知识告诉我们每个单词是啥,没告诉我们是什么意思。还有就是,怎么融合这些表示呢?

第一步:通过one-hot编码。w=[0,0,1,0,0]。其中1是表示w的独一无二的维度。

但是缺点就是没有语义信息。正交表示就没有语义信息。

"出现在相似位置和相似语境中的单词具有语义相关性!"这就是分布式假设

例子

假设每个维度是代表某种属性(而不是one-hot中每种属性都是一个单词),那么通过在每个维度上各种属性的"调和",

就能够获取一个单词,相似的单词在某几个"属性上"类似,就会在向量空间距离变近。不相似的单词夹角就会很大。

避免了每个维度大量出现0(one-hot的缺陷)

那么问题就来了,每个维度代表什么属性怎么设计,太难了,就让神经网络自己设计,不需要程序员设计了。

为啥不让词嵌入作为模型参数呢??在训练中自己去更新!正是我们做的事情。

但是词嵌入可解释性不强,也就是说,训练出来,每个维度代表什么含义,不清楚。

但结果就是,近义词在潜在语义维度上确实相近,却难以解释。

总而言之,词嵌入是单词的语义解释。是高效的语义信息编码。

当然可以去"embedding"其他任何事情:词性标签,解析树。

特征嵌入的思想是这个领域的核心。

pytorch

通过PyTorch来进行Embedding。

类似于通过one-hot来对单词进行索引,我们要使用Embedding去给每个单词定义索引。

这是lookup table的关键所在。

这样,embedding被存入|V|*D的矩阵,D是embedding的维度,就比如单词的索引被存入矩阵的第i行。

在下面的代码中,单词到索引的映射是一个叫做word_to_ix的字典。

模块是nn.Embedding,参数是词汇表的size,和嵌入的维度

而且要注意,对于表的索引,使用torch.LongTensor,因为索引是整数,不是浮点数

CONTEXT_SIZE = 2
EMBEDDING_DIM = 10
# We will use Shakespeare Sonnet 2
test_sentence = """When forty winters shall besiege thy brow,
And dig deep trenches in thy beauty's field,
Thy youth's proud livery so gazed on now,
Will be a totter'd weed of small worth held:
Then being asked, where all thy beauty lies,
Where all the treasure of thy lusty days;
To say, within thine own deep sunken eyes,
Were an all-eating shame, and thriftless praise.
How much more praise deserv'd thy beauty's use,
If thou couldst answer 'This fair child of mine
Shall sum my count, and make my old excuse,'
Proving his beauty by succession thine!
This were to be new made when thou art old,
And see thy blood warm when thou feel'st it cold.""".split()
# we should tokenize the input, but we will ignore that for now
# build a list of tuples. Each tuple is ([ word_i-2, word_i-1 ], target word)
trigrams = [([test_sentence[i], test_sentence[i + 1]], test_sentence[i + 2])
for i in range(len(test_sentence) - 2)]
# print the first 3, just so you can see what they look like
print(trigrams[:3]) vocab = set(test_sentence)#得到单词的数量,编码的基础
word_to_ix = {word: i for i, word in enumerate(vocab)}#首先对单词进行最简单的编码 class NGramLanguageModeler(nn.Module): def __init__(self, vocab_size, embedding_dim, context_size):
super(NGramLanguageModeler, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embedding_dim)#其实就是词嵌入矩阵而已
self.linear1 = nn.Linear(context_size * embedding_dim, 128)#由于是利用前面两个词进行预测的,因此需要将得到的单词拼接起来,其实也可以加和,求平均什么的
self.linear2 = nn.Linear(128, vocab_size)#去分类 def forward(self, inputs):
embeds = self.embeddings(inputs).view((1, -1))#通过嵌入矩阵并且合并
out = F.relu(self.linear1(embeds))
out = self.linear2(out)
log_probs = F.log_softmax(out)
return log_probs losses = []
loss_function = nn.NLLLoss()
model = NGramLanguageModeler(len(vocab), EMBEDDING_DIM, CONTEXT_SIZE)
optimizer = optim.SGD(model.parameters(), lr=0.001) for epoch in range(10):
total_loss = torch.Tensor([0])
for context, target in trigrams: # Step 1. Prepare the inputs to be passed to the model (i.e, turn the words
# into integer indices and wrap them in variables)
context_idxs = [word_to_ix[w] for w in context]
context_var = autograd.Variable(torch.LongTensor(context_idxs)) # Step 2. Recall that torch *accumulates* gradients. Before passing in a
# new instance, you need to zero out the gradients from the old
# instance
model.zero_grad() # Step 3. Run the forward pass, getting log probabilities over next
# words
log_probs = model(context_var) # Step 4. Compute your loss function. (Again, Torch wants the target
# word wrapped in a variable)
loss = loss_function(log_probs, autograd.Variable(
torch.LongTensor([word_to_ix[target]]))) # Step 5. Do the backward pass and update the gradient
loss.backward()
optimizer.step() total_loss += loss.data
losses.append(total_loss)
print(losses) # The loss decreased every iteration over the training data!

总结

之前还是一直没有搞清词向量的本质,拿捏不定,其实词向量训练的方法很多,但本质的思想是类似的。就是设置一个查询表,也就是词嵌入矩阵。通过这个查询表,将原始稀疏的one-hot编码成稠密向量。而查询表需要通过训练得到,也就是网络中的参数。



那么最终使用的就是这个权重矩阵的每行来表示对应位置的词向量,和原始的索引相乘只是一个查表的操作。

Word Embeddings: Encoding Lexical Semantics(译文)的更多相关文章

  1. Word Embeddings: Encoding Lexical Semantics

    Word Embeddings: Encoding Lexical Semantics Getting Dense Word Embeddings Word Embeddings in Pytorch ...

  2. 翻译 | Improving Distributional Similarity with Lessons Learned from Word Embeddings

    翻译 | Improving Distributional Similarity with Lessons Learned from Word Embeddings 叶娜老师说:"读懂论文的 ...

  3. [C5W2] Sequence Models - Natural Language Processing and Word Embeddings

    第二周 自然语言处理与词嵌入(Natural Language Processing and Word Embeddings) 词汇表征(Word Representation) 上周我们学习了 RN ...

  4. deeplearning.ai 序列模型 Week 2 NLP & Word Embeddings

    1. Word representation One-hot representation的缺点:把每个单词独立对待,导致对相关词的泛化能力不强.比如训练出“I want a glass of ora ...

  5. 论文阅读笔记 Word Embeddings A Survey

    论文阅读笔记 Word Embeddings A Survey 收获 Word Embedding 的定义 dense, distributed, fixed-length word vectors, ...

  6. 课程五(Sequence Models),第二 周(Natural Language Processing & Word Embeddings) —— 1.Programming assignments:Operations on word vectors - Debiasing

    Operations on word vectors Welcome to your first assignment of this week! Because word embeddings ar ...

  7. [IR] Word Embeddings

    From: https://www.youtube.com/watch?v=pw187aaz49o Ref: http://blog.csdn.net/abcjennifer/article/deta ...

  8. Word Embeddings

    能够充分意识到W的这些属性不过是副产品而已是很重要的.我们没有尝试着让相似的词离得近.我们没想把类比编码进不同的向量里.我们想做的不过是一个简单的任务,比如预测一个句子是不是成立的.这些属性大概也就是 ...

  9. Papers of Word Embeddings

    首先解释一下什么叫做embedding.举个例子:地图就是对于现实地理的embedding,现实的地理地形的信息其实远远超过三维 但是地图通过颜色和等高线等来最大化表现现实的地理信息. embeddi ...

随机推荐

  1. 将 Sidecar 容器带入新的阶段

    作者 | 徐迪.张晓宇 导读:本文根据徐迪和张晓宇在 KubeCon NA 2019 大会分享整理.分享将会从以下几个方面进行切入:首先会简单介绍一下什么是 Sidecar 容器:其次,会分享几个阿里 ...

  2. flask的url处理器(url_defaults和url_value_preprocessor)

    url处理器的作用:对于一部分资源, 你并不是很清楚该如何设定其 URL 相同的部分.例如可能有一些URL包含了几个字母来指定的多国语言语种,但是你不想在每个函数里都手动识别到底是哪个语言 rom f ...

  3. javascript DOM 编程艺术 札记2 平稳退化

    定义 指的是即便浏览器不支持javascript,页面的基础展示功能也不会受到影响的做法. 不能平稳退化的实例 javascript:这种伪协议,它可以通过链接调用javascript函数.比如< ...

  4. 用c++ 给易语言写支持库学习记录

    废话我就不对说 直接开始 易语言官方下载的易语言安装路径下 有一个SDK文件夹 我们点进入cpp文件夹里面提供是c++的SDK elib文件夹里就是sdk 我们新建一个win32项目 这里我用的是VS ...

  5. VC/c++版本获取现行时间戳精确到毫秒

    时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数.通俗的讲, 时间戳是一份能够表示一份数据在一个特定时间点已经存在的完 ...

  6. 【题解】P4755 Beautiful Pair(启发式合并的思路+分治=启发式分治)

    [题解]P4755 Beautiful Pair upd: 之前一个first second烦了,现在AC了 由于之前是直接抄std写的,所以没有什么心得体会,今天自己写写发现 不知道为啥\(90\) ...

  7. SCU 4439 Vertex Cover|最小点覆盖

    传送门 Vertex Cover frog has a graph with n vertices v(1),v(2),…,v(n)v(1),v(2),…,v(n) and m edges (v(a1 ...

  8. 【转】python get-pip.py could not find a version that satisfies

    转:https://blog.csdn.net/yanlisuo/article/details/81357305 转:https://blog.csdn.net/dyrlovewc/article/ ...

  9. java小项目之:象棋,羡慕你们有对象的!

    象棋,是我国传统棋类益智游戏,在中国有着悠久的历史,属于二人对抗性游戏的一种,由于用具简单,趣味性强,成为流行极为广泛的棋艺活动.中国象棋是中国棋文化也是中华民族的文化瑰宝. 象棋还有很多口诀,这是最 ...

  10. 【阿里云IoT+YF3300】11.物联网多设备快速通信级联

    我们见到的很多物联网设备,大都是“一跳”上网,所谓的“一跳”就是设备直接上网,内嵌物联网模块或者通过DTU直接上网.其实稍微复杂的物联网现场,往往网关下面连接若干物联网设备(如下图),并且这些物联网设 ...