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
相关推荐
盟接之桥2 分钟前
当大模型遇见线束制造:不是通用AI,而是行业AI
大数据·网络·人工智能·安全·制造
databook10 分钟前
从手动检查到自动监控:一个数据质量工作流的实现
后端·python·数据分析
归秋14221 分钟前
2026 企业 AI 办公工具选型指南:从评估框架到产品适配
大数据·运维·人工智能
冬奇Lab34 分钟前
开源项目第229期:e2e — 用自然语言写 E2E 测试,还能把 Agent 跑过的操作录成‘回放缓存‘免模型调用
人工智能·测试
东风破_35 分钟前
从 Neo4j 到 GraphRAG:用 Text-to-Cypher 构建图检索 RAG
人工智能·后端
冬奇Lab36 分钟前
LLM 自动化测试系列(05):移动端自动化(一)——ARTEMIS 的双模式架构拆解
人工智能·测试
DisonTangor37 分钟前
llama.cpp 新特性:决策模型
人工智能·开源·aigc
鲲穹AI种草38 分钟前
AI 生成 PPT 工具怎么选?鲲穹 PPT 功能实测与横向对比
人工智能·powerpoint
AI技术新视界1 小时前
Strata 的工作原理
人工智能·推理引擎·本地ai
2501_926978331 小时前
给自指系统接一个外部锚 —— 一个关于「用 AI 观察自己」的方法
人工智能·经验分享·笔记·机器学习·ai写作