赞
踩
参考self-attention 的 pytorch 实现 - 云+社区 - 腾讯云
问题
基于条件的卷积GAN 在那些约束较少的类别中生成的图片较好,比如大海,天空等;但是在那些细密纹理,全局结构较强的类别中生成的图片不是很好,如人脸(可能五官不对应),狗(可能狗腿数量有差,或者毛色不协调)。
可能的原因
大部分卷积神经网络都严重依赖于局部感受野,而无法捕捉全局特征。另外,在多次卷积之后,细密的纹理特征逐渐消失。
SA-GAN解决思路
不仅仅依赖于局部特征,也利用全局特征,通过将不同位置的特征图结合起来(转置就可以结合不同位置的特征)。
- ##############################
- # self attention layer
- # author Xu Mingle
- # time Feb 18, 2019
- ##############################
- import torch.nn.Module
- import torch
- import torch.nn.init
- def init_conv(conv, glu=True):
- init.xavier_uniform_(conv.weight)
- if conv.bias is not None:
- conv.bias.data.zero_()
-
- class SelfAttention(nn.Module):
- r"""
- Self attention Layer.
- Source paper: https://arxiv.org/abs/1805.08318
- """
- def __init__(self, in_dim, activation=F.relu):
- super(SelfAttention, self).__init__()
- self.chanel_in = in_dim
- self.activation = activation
-
- self.f = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8 , kernel_size=1)
- self.g = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8 , kernel_size=1)
- self.h = nn.Conv2d(in_channels=in_dim, out_channels=in_dim , kernel_size=1)
-
- self.gamma = nn.Parameter(torch.zeros(1))
-
- self.softmax = nn.Softmax(dim=-1)
-
- init_conv(self.f)
- init_conv(self.g)
- init_conv(self.h)
-
- def forward(self, x):
- """
- inputs :
- x : input feature maps( B X C X W X H)
- returns :
- out : self attention feature maps
-
- """
- m_batchsize, C, width, height = x.size()
-
- f = self.f(x).view(m_batchsize, -1, width * height) # B * (C//8) * (W * H)
- g = self.g(x).view(m_batchsize, -1, width * height) # B * (C//8) * (W * H)
- h = self.h(x).view(m_batchsize, -1, width * height) # B * C * (W * H)
-
- attention = torch.bmm(f.permute(0, 2, 1), g) # B * (W * H) * (W * H)
- attention = self.softmax(attention)
-
- self_attetion = torch.bmm(h, attention) # B * C * (W * H)
- self_attetion = self_attetion.view(m_batchsize, C, width, height) # B * C * W * H
-
- out = self.gamma * self_attetion + x
- return out

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。