pytorch代码实现之CoordConv卷积

CoordConv卷积

在深度学习领域,几乎没有什么想法能像卷积那样产生如此大的影响。对于任何涉及像素或空间表示的问题,普遍的直觉认为卷积神经网络可能是合适的。在本文中,我们通过看似平凡的坐标变换问题展示了一个惊人的反例,该问题只需要学习(x, y)笛卡尔空间中的坐标与单热像素空间中的坐标之间的映射。虽然卷积网络似乎适合这项任务,但我们表明它们失败得很明显。

CoordConv的工作原理是通过使用额外的坐标通道让卷积访问自己的输入坐标。在不牺牲普通卷积的计算和参数效率的情况下,CoordConv允许网络根据最终任务的需要学习完全的平移不变性或不同程度的平移依赖性。CoordConv解决了坐标变换问题,具有很好的泛化性,比convolution的参数少10-100倍,速度快150倍。

原文地址:An intriguing failing of convolutional neural networks and the CoordConv solution

代码实现:

matlab 复制代码
class AddCoords(nn.Module):
    def __init__(self, with_r=False):
        super().__init__()
        self.with_r = with_r

    def forward(self, input_tensor):
        """
        Args:
            input_tensor: shape(batch, channel, x_dim, y_dim)
        """
        batch_size, _, x_dim, y_dim = input_tensor.size()

        xx_channel = torch.arange(x_dim).repeat(1, y_dim, 1)
        yy_channel = torch.arange(y_dim).repeat(1, x_dim, 1).transpose(1, 2)

        xx_channel = xx_channel.float() / (x_dim - 1)
        yy_channel = yy_channel.float() / (y_dim - 1)

        xx_channel = xx_channel * 2 - 1
        yy_channel = yy_channel * 2 - 1

        xx_channel = xx_channel.repeat(batch_size, 1, 1, 1).transpose(2, 3)
        yy_channel = yy_channel.repeat(batch_size, 1, 1, 1).transpose(2, 3)

        ret = torch.cat([
            input_tensor,
            xx_channel.type_as(input_tensor),
            yy_channel.type_as(input_tensor)], dim=1)

        if self.with_r:
            rr = torch.sqrt(torch.pow(xx_channel.type_as(input_tensor) - 0.5, 2) + torch.pow(yy_channel.type_as(input_tensor) - 0.5, 2))
            ret = torch.cat([ret, rr], dim=1)

        return ret

class CoordConv(nn.Module):

    def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, with_r=False):
        super().__init__()
        self.addcoords = AddCoords(with_r=with_r)
        in_channels += 2
        if with_r:
            in_channels += 1
        self.conv = Conv(in_channels, out_channels, k=kernel_size, s=stride)

    def forward(self, x):
        x = self.addcoords(x)
        x = self.conv(x)
        return x
相关推荐
gaosushexiangji35 分钟前
利用sCMOS科学相机测量激光散射强度
大数据·人工智能·数码相机·计算机视觉
ai小鬼头2 小时前
AIStarter新版重磅来袭!永久订阅限时福利抢先看
人工智能·开源·github
说私域2 小时前
从品牌附庸到自我表达:定制开发开源AI智能名片S2B2C商城小程序赋能下的营销变革
人工智能·小程序
飞哥数智坊3 小时前
新版定价不够用,Cursor如何退回旧版定价
人工智能·cursor
12点一刻3 小时前
搭建自动化工作流:探寻解放双手的有效方案(2)
运维·人工智能·自动化·deepseek
未来之窗软件服务3 小时前
东方仙盟AI数据中间件使用教程:开启数据交互与自动化应用新时代——仙盟创梦IDE
运维·人工智能·自动化·仙盟创梦ide·东方仙盟·阿雪技术观
chao_7893 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
烛阴4 小时前
Python装饰器解除:如何让被装饰的函数重获自由?
前端·python
JNU freshman4 小时前
计算机视觉速成 之 概述
人工智能·计算机视觉
noravinsc4 小时前
django 一个表中包括id和parentid,如何通过parentid找到全部父爷id
python·django·sqlite