Pytorch实现TripletAttention
Posted AI浩
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pytorch实现TripletAttention相关的知识,希望对你有一定的参考价值。
# !/usr/bin/env python
# -- coding: utf-8 --
import torch
import torch.nn as nn
import torchvision
class ChannelPool(nn.Module):
def forward(self, x):
return torch.cat( (torch.max(x,1)[0].unsqueeze(1), torch.mean(x,1).unsqueeze(1)), dim=1 )
class SpatialGate(nn.Module):
def __init__(self):
super(SpatialGate, self).__init__()
self.channel_pool = ChannelPool()
self.conv = nn.Sequential(
nn.Conv2d(in_channels=2, out_channels=1, kernel_size=7, stride=1, padding=3),
nn.BatchNorm2d(1)
)
self.sigmod = nn.Sigmoid()
def forward(self, x):
out = self.conv(self.channel_pool(x))
return out * self.sigmod(out)
class TripletAttention(nn.Module):
def __init__(self, spatial=True):
super(TripletAttention, self).__init__()
self.spatial = spatial
self.height_gate = SpatialGate()
self.width_gate = SpatialGate()
if self.spatial:
self.spatial_gate = SpatialGate()
def forward(self, x):
x_perm1 = x.permute(0, 2, 1, 3).contiguous()
x_out1 = self.height_gate(x_perm1)
x_out1 = x_out1.permute(0, 2, 1, 3).contiguous()
x_perm2 = x.permute(0, 3, 2, 1).contiguous()
x_out2 = self.width_gate(x_perm2)
x_out2 = x_out2.permute(0, 3, 2, 1).contiguous()
if self.spatial:
x_out3 = self.spatial_gate(x)
return (1/3) * (x_out1 + x_out2 + x_out3)
else:
return (1/2) * (x_out1 + x_out2)
if __name__=='__main__':
model = TripletAttention()
print(model)
input = torch.randn(1, 16, 256, 256)
out = model(input)
print(out.shape)
以上是关于Pytorch实现TripletAttention的主要内容,如果未能解决你的问题,请参考以下文章
基于pytorch使用实现CNN 如何使用pytorch构建CNN卷积神经网络