pytorch-- Attention Mechanism
1. paper: Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation
Encoder
每个时刻输入一个词,隐藏层状态根据公式ht=f(ht−1,xt)改变。其中激活函数f可以是sigmod,tanh,ReLU,sotfplus等。
读完序列的每一个词之后,会得到一个固定长度向量c=tanh(VhN)
Decoder
由结构图可以看出,t时刻的隐藏层状态ht由ht−1,yt−1,c决定:ht=f(ht−1,yt−1,c),其中h0=tanh(V′c)
最后的输出yt是由ht,yt−1,c决定
P=(yt|yt−1,yt−2,...,y1,c)=g(ht,yt−1,c)
以上,f,gf,g都是激活函数,其中g一般是softmax
对此我在pytoch环境下进行实现seq2seq最初版的模型:
(参考:https://github.com/graykode/nlp-tutorial)
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable dtype = torch.FloatTensor
# S: Symbol that shows starting of decoding input
# E: Symbol that shows ending of decoding output
# P: Symbol that will fill in blank sequence if current batch data size is short than time steps char_arr = [c for c in 'SEPabcdefghijklmnopqrstuvwxyz']
num_dic = {n: i for i, n in enumerate(char_arr)} seq_data = [['man', 'women'], ['black', 'white'], ['king', 'queen'], ['girl', 'boy'], ['up', 'down'], ['high', 'low']] # Seq2Seq Parameter
n_step = 5
n_hidden = 128
n_class = len(num_dic) #
batch_size = len(seq_data) # def make_batch(seq_data):
input_batch, output_batch, target_batch = [], [], [] for seq in seq_data:
for i in range(2):
seq[i] = seq[i] + 'P' * (n_step - len(seq[i])) input = [num_dic[n] for n in seq[0]]
output = [num_dic[n] for n in ('S' + seq[1])]
target = [num_dic[n] for n in (seq[1] + 'E')] input_batch.append(np.eye(n_class)[input])
output_batch.append(np.eye(n_class)[output])
target_batch.append(target) # not one-hot # make tensor
return Variable(torch.Tensor(input_batch)), Variable(torch.Tensor(output_batch)), Variable(torch.LongTensor(target_batch)) # Model
class Seq2Seq(nn.Module):
def __init__(self):
super(Seq2Seq, self).__init__() self.enc_cell = nn.RNN(input_size=n_class, hidden_size=n_hidden, dropout=0.5)
self.dec_cell = nn.RNN(input_size=n_class, hidden_size=n_hidden, dropout=0.5)
self.fc = nn.Linear(n_hidden, n_class) def forward(self, enc_input, enc_hidden, dec_input):
enc_input = enc_input.transpose(0, 1) # enc_input: [max_len(=n_step, time step), batch_size, n_class]
dec_input = dec_input.transpose(0, 1) # dec_input: [max_len(=n_step, time step), batch_size, n_class] # enc_states : [num_layers(=1) * num_directions(=1), batch_size, n_hidden]
_, enc_states = self.enc_cell(enc_input, enc_hidden)
# outputs : [max_len+1(=6), batch_size, num_directions(=1) * n_hidden(=128)]
outputs, _ = self.dec_cell(dec_input, enc_states) model = self.fc(outputs) # model : [max_len+1(=6), batch_size, n_class]
return model input_batch, output_batch, target_batch = make_batch(seq_data) model = Seq2Seq()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001) for epoch in range(5000):
# make hidden shape [num_layers * num_directions, batch_size, n_hidden]
hidden = Variable(torch.zeros(1, batch_size, n_hidden)) # input_batch : [batch_size, max_len(=n_step, time step), n_class]
# output_batch : [batch_size, max_len+1(=n_step, time step) (becase of 'S' or 'E'), n_class]
# target_batch : [batch_size, max_len+1(=n_step, time step)], not one-hot
output = model(input_batch, hidden, output_batch)
# output : [max_len+1, batch_size, n_class]
output = output.transpose(0, 1) # [batch_size, max_len+1(=6), n_class]
loss = 0
for i in range(0, len(target_batch)):
# output[i] : [max_len+1, n_class, target_batch[i] : max_len+1]
loss += criterion(output[i], target_batch[i])
if (epoch + 1) % 1000 == 0:
print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.6f}'.format(loss)) optimizer.zero_grad()
loss.backward()
optimizer.step() # Test
def translate(word):
input_batch, output_batch, _ = make_batch([[word, 'P' * len(word)]]) # make hidden shape [num_layers * num_directions, batch_size, n_hidden]
hidden = Variable(torch.zeros(1, 1, n_hidden))
output = model(input_batch, hidden, output_batch)
# output : [max_len+1(=6), batch_size(=1), n_class] predict = output.data.max(2, keepdim=True)[1] # select n_class dimension
decoded = [char_arr[i] for i in predict]
end = decoded.index('E')
translated = ''.join(decoded[:end]) return translated.replace('P', '') print('test')
print('man ->', translate('man'))
print('mans ->', translate('mans'))
print('king ->', translate('king'))
print('black ->', translate('black'))
print('upp ->', translate('upp'))
之后,在seq2seq模型基础上,提出了attention机制。
论文: NEURAL MACHINE TRANSLATION BY JOINTLY LEARNING TO ALIGN AND TRANSLATE
pytorch-- Attention Mechanism的更多相关文章
- (转)注意力机制(Attention Mechanism)在自然语言处理中的应用
注意力机制(Attention Mechanism)在自然语言处理中的应用 本文转自:http://www.cnblogs.com/robert-dlut/p/5952032.html 近年来,深度 ...
- 注意力机制(Attention Mechanism)在自然语言处理中的应用
注意力机制(Attention Mechanism)在自然语言处理中的应用 近年来,深度学习的研究越来越深入,在各个领域也都获得了不少突破性的进展.基于注意力(attention)机制的神经网络成为了 ...
- 深度学习之注意力机制(Attention Mechanism)和Seq2Seq
这篇文章整理有关注意力机制(Attention Mechanism )的知识,主要涉及以下几点内容: 1.注意力机制是为了解决什么问题而提出来的? 2.软性注意力机制的数学原理: 3.软性注意力机制. ...
- 课程五(Sequence Models),第三周(Sequence models & Attention mechanism) —— 1.Programming assignments:Neural Machine Translation with Attention
Neural Machine Translation Welcome to your first programming assignment for this week! You will buil ...
- [C5W3] Sequence Models - Sequence models & Attention mechanism
第三周 序列模型和注意力机制(Sequence models & Attention mechanism) 基础模型(Basic Models) 在这一周,你将会学习 seq2seq(sequ ...
- 模型汇总24 - 深度学习中Attention Mechanism详细介绍:原理、分类及应用
模型汇总24 - 深度学习中Attention Mechanism详细介绍:原理.分类及应用 lqfarmer 深度学习研究员.欢迎扫描头像二维码,获取更多精彩内容. 946 人赞同了该文章 Atte ...
- 【转载】Attention Mechanism in Deep Learning
本篇随笔为转载,原文地址:知乎,深度学习中Attention Mechanism详细介绍:原理.分类及应用.参考链接:深度学习中的注意力机制. Attention是一种用于提升基于RNN(LSTM或G ...
- 吴恩达《深度学习》-第五门课 序列模型(Sequence Models)-第三周 序列模型和注意力机制(Sequence models & Attention mechanism)-课程笔记
第三周 序列模型和注意力机制(Sequence models & Attention mechanism) 3.1 序列结构的各种序列(Various sequence to sequence ...
- 论文解读(GSAT)《Interpretable and Generalizable Graph Learning via Stochastic Attention Mechanism》
论文信息 论文标题:Interpretable and Generalizable Graph Learning via Stochastic Attention Mechanism论文作者:Siqi ...
- Attention Mechanism in Computer Vision
前言 本文系统全面地介绍了Attention机制的不同类别,介绍了每个类别的原理.优缺点. 欢迎关注公众号CV技术指南,专注于计算机视觉的技术总结.最新技术跟踪.经典论文解读.CV招聘信息. 概 ...
随机推荐
- react-mockjs
2020-01-17 react-mockjs 使用 最近参加了公司的一个新的项目,前后端同时开发,这时后端提供不了前端接口,那么就要靠咱们前端自己mock数据啦. 用到mock 数据的工具是 moc ...
- Java 基础(一)| 使用泛型的正确姿势
前言 为跳槽面试做准备,今天开始进入 Java 基础的复习.希望基础不好的同学看完这篇文章,能掌握泛型,而基础好的同学权当复习,希望看完这篇文章能够起一点你的青涩记忆. 一.什么是泛型 泛型,即&qu ...
- dp-划分数 (递推)
问题描述 : 有 n 个无区别的物品 , 将他们分成 不超过 m 堆, 问有多少种分法 ? 例如 : n = 4 , m = 3 , 则总共有的分法是 1 + 2 +1 , 0 + 1 + 3 , 0 ...
- Tarjin + 缩点
链接:https://www.nowcoder.com/acm/contest/81/C来源:牛客网 题目描述 给出一个 0 ≤ N ≤ 105 点数.0 ≤ M ≤ 105 边数的有向图, 输出一个 ...
- TornadoFx学习笔记(1)——常用的代码片段
Tornadofx是基于JavaFx的一个kotlin实现的框架 之后看情况补充.. 1.读取resources文件夹中的文件 如图 想要读取config.properties文件,有两种方法 在cl ...
- 基于AOP和ThreadLocal实现的一个简单Http API日志记录模块
Log4a 基于AOP和ThreadLocal实现的一个简单Http API日志记录模块 github地址 : https://github.com/EalenXie/log4a 在API每次被请求时 ...
- PSP第一次总结
项目计划总结 周活动总结表 姓名:王金萱 ...
- NOIP游记
好像很久没写博客了诶,NOIP考完,写篇游记吧XD Day 1 紧张紧张,去年第一题小凯的疑惑坑煞我也,今年怕不是什么大凯的疑惑吧... 进考场,重启,下软件,在键盘上猛敲RP++ 发密码辣,FeiX ...
- Qt Installer Framework翻译(7-5)
操作 这些操作由组件和控制脚本准备,并由安装程序执行. 注意:操作是通过线程执行的. 在内部,每个操作都有一个DO步骤,包含有关安装程序的说明,以及一个UNDO步骤,包含有关卸载程序的说明. 操作总结 ...
- P4452 [国家集训队]航班安排(最大费用最大流)
P4452 [国家集训队]航班安排 题目传送门 解题思路: 感觉题面让人有很多误解,就是说有k架飞机在0点从0号机场起飞,在t时刻返回机场,给出空载飞行的时间和花费以及m个包机请求的花费和起始时间和终 ...