Co Attention注意力机制实现

2024-04-24 20:32

本文主要是介绍Co Attention注意力机制实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

“Hierarchical Question-Image Co-Attention for Visual Question Answering”中的图像和文本间的Co Attention协同注意力实现

参考:

https://github.com/SkyOL5/VQA-CoAttention/blob/master/coatt/coattention_net.py

https://github.com/Zhangtd/Models-reproducing/blob/master/NIPS2016/selfDef.py

Co Attention示意图如下:

有两种实现方式,分别为Parallel co-attention mechanism和Alternating co-attention mechanism

基于PyTorch实现Parallel co-attention mechanism,代码如下:

from typing import Dict, Optionalimport numpy as np
import torch.nn as nn
import torch
import torch.nn.functional as F
from torch import Tensordef create_src_lengths_mask(batch_size: int, src_lengths: Tensor, max_src_len: Optional[int] = None
):"""Generate boolean mask to prevent attention beyond the end of sourceInputs:batch_size : intsrc_lengths : [batch_size] of sentence lengthsmax_src_len: Optionally override max_src_len for the maskOutputs:[batch_size, max_src_len]"""if max_src_len is None:max_src_len = int(src_lengths.max())src_indices = torch.arange(0, max_src_len).unsqueeze(0).type_as(src_lengths)src_indices = src_indices.expand(batch_size, max_src_len)src_lengths = src_lengths.unsqueeze(dim=1).expand(batch_size, max_src_len)# returns [batch_size, max_seq_len]return (src_indices < src_lengths).int().detach()def masked_softmax(scores, src_lengths, src_length_masking=True):"""Apply source length masking then softmax.Input and output have shape bsz x src_len"""if src_length_masking:bsz, max_src_len = scores.size()# print('bsz:', bsz)# compute maskssrc_mask = create_src_lengths_mask(bsz, src_lengths)# Fill pad positions with -infscores = scores.masked_fill(src_mask == 0, -np.inf)# Cast to float and then back again to prevent loss explosion under fp16.return F.softmax(scores.float(), dim=-1).type_as(scores)class ParallelCoAttentionNetwork(nn.Module):def __init__(self, hidden_dim, co_attention_dim, src_length_masking=True):super(ParallelCoAttentionNetwork, self).__init__()self.hidden_dim = hidden_dimself.co_attention_dim = co_attention_dimself.src_length_masking = src_length_maskingself.W_b = nn.Parameter(torch.randn(self.hidden_dim, self.hidden_dim))self.W_v = nn.Parameter(torch.randn(self.co_attention_dim, self.hidden_dim))self.W_q = nn.Parameter(torch.randn(self.co_attention_dim, self.hidden_dim))self.w_hv = nn.Parameter(torch.randn(self.co_attention_dim, 1))self.w_hq = nn.Parameter(torch.randn(self.co_attention_dim, 1))def forward(self, V, Q, Q_lengths):""":param V: batch_size * hidden_dim * region_num, eg B x 512 x 196:param Q: batch_size * seq_len * hidden_dim, eg B x L x 512:param Q_lengths: batch_size:return:batch_size * 1 * region_num, batch_size * 1 * seq_len,batch_size * hidden_dim, batch_size * hidden_dim"""# (batch_size, seq_len, region_num)C = torch.matmul(Q, torch.matmul(self.W_b, V))# (batch_size, co_attention_dim, region_num)H_v = nn.Tanh()(torch.matmul(self.W_v, V) + torch.matmul(torch.matmul(self.W_q, Q.permute(0, 2, 1)), C))# (batch_size, co_attention_dim, seq_len)H_q = nn.Tanh()(torch.matmul(self.W_q, Q.permute(0, 2, 1)) + torch.matmul(torch.matmul(self.W_v, V), C.permute(0, 2, 1)))# (batch_size, 1, region_num)a_v = F.softmax(torch.matmul(torch.t(self.w_hv), H_v), dim=2)# (batch_size, 1, seq_len)a_q = F.softmax(torch.matmul(torch.t(self.w_hq), H_q), dim=2)# # (batch_size, 1, seq_len)masked_a_q = masked_softmax(a_q.squeeze(1), Q_lengths, self.src_length_masking).unsqueeze(1)# (batch_size, hidden_dim)v = torch.squeeze(torch.matmul(a_v, V.permute(0, 2, 1)))# (batch_size, hidden_dim)q = torch.squeeze(torch.matmul(masked_a_q, Q))return a_v, masked_a_q, v, q

测试代码如下:

pcan = ParallelCoAttentionNetwork(6, 5)
v = torch.randn((5, 6, 10))
q = torch.randn(5, 8, 6)
q_lens = torch.LongTensor([3, 4, 5, 8, 2])
a_v, a_q, v, q = pcan(v, q, q_lens)
print(a_v)
print(a_v.shape)
print(a_q)
print(a_q.shape)
print(v)
print(v.shape)
print(q)
print(q.shape)

效果如下:

tensor([[[9.2527e-04, 1.1542e-03, 1.1542e-03, 1.1542e-03, 2.0009e-02,9.2527e-04, 4.0845e-02, 8.8328e-01, 1.1958e-03, 4.9358e-02]],[[4.5501e-01, 8.6522e-02, 8.6522e-02, 1.7235e-05, 3.8831e-03,2.5070e-04, 9.0637e-05, 4.0010e-03, 2.0196e-03, 3.6169e-01]],[[8.8455e-03, 7.2149e-04, 1.7595e-04, 2.1307e-04, 7.0610e-01,1.3427e-01, 4.3360e-04, 4.0731e-02, 4.0731e-02, 6.7774e-02]],[[4.0013e-01, 2.3081e-02, 3.8406e-02, 4.3583e-03, 9.9425e-05,3.8398e-02, 9.9425e-05, 9.4912e-02, 4.0013e-01, 3.9162e-04]],[[3.1121e-02, 8.0567e-05, 4.0445e-01, 1.4391e-03, 8.0567e-05,4.0445e-01, 7.6909e-02, 2.4837e-04, 4.3044e-03, 7.6909e-02]]],grad_fn=<SoftmaxBackward>)
torch.Size([5, 1, 10])
tensor([[[0.3466, 0.3267, 0.3267, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],[[0.2256, 0.3276, 0.2237, 0.2232, 0.0000, 0.0000, 0.0000, 0.0000]],[[0.1761, 0.2254, 0.2254, 0.1823, 0.1908, 0.0000, 0.0000, 0.0000]],[[0.1292, 0.1411, 0.1411, 0.1100, 0.1292, 0.1100, 0.1101, 0.1292]],[[0.5284, 0.4716, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]],grad_fn=<UnsqueezeBackward0>)
torch.Size([5, 1, 8])
tensor([[-0.7862,  1.0180,  0.1585,  0.4961, -1.5916, -0.3553],[ 0.3624, -0.2036,  0.2993, -0.4440,  0.2494,  1.4896],[ 0.1695, -0.2286,  0.4431,  0.6027, -1.6116,  0.0566],[ 0.2004,  0.8219, -0.2115, -0.6428,  0.3486,  1.3802],[ 1.4024, -0.1860,  0.1685,  0.2352, -0.4956,  1.0010]],grad_fn=<SqueezeBackward0>)
torch.Size([5, 6])
tensor([[ 0.3757,  0.1662,  0.2181,  0.0787,  0.0110, -0.5938],[-0.6106,  0.4000,  0.6068, -0.4054,  0.0193, -0.1147],[ 0.3877, -0.1800,  1.2430, -0.4881, -0.3598, -0.3592],[-0.3799, -0.3262,  0.0745, -0.2856,  0.0221, -0.1749],[ 0.1159, -0.4949, -0.5576, -0.6870, -1.2895,  0.0421]],grad_fn=<SqueezeBackward0>)
torch.Size([5, 6])

这篇关于Co Attention注意力机制实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/932765

相关文章

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os