【pytorch】1x1卷积

对image进行1x1卷积,输入为 ( b a t c h , C , H , W ) (batch, C, H, W) (batch,C,H,W),如下例子,输入为 ( 4 , 3 , 225 , 225 ) (4, 3, 225, 225) (4,3,225,225)的图片,输出为 ( 4 , 256 , 225 , 225 ) (4, 256, 225, 225) (4,256,225,225)的特征图

import torch
import torch.nn as nn

batch = 4
C = 3
H = W = 225
x = torch.rand((batch, C, H, W))
conv = nn.Conv2d(in_channels=C, out_channels=256, kernel_size=1, stride=1, padding=0)
out = conv(x)
print(out.shape)  # (4, 256, 225, 225)

对3维张量进行1x1卷积,由于pytorch进行2D卷积要求输入是4维张量,因此要对形如 ( b a t c h , C , N ) (batch,C,N) (batch,C,N)的张量进行1x1卷积时要先将其扩展一个维度,可以扩展为 ( b a t c h , C , 1 , N ) (batch,C,1,N) (batch,C,1,N) ( b a t c h , C , N , 1 ) (batch,C,N,1) (batch,C,N,1)再进行1x1卷积,结果都是一样的,例如

import torch
import torch.nn as nn

torch.manual_seed(28)
x = torch.rand((4, 128, 2048))
conv = nn.Conv2d(128, 256, kernel_size=1, stride=1)

# 扩展最后一个维度和倒数第二个维度结果都是一样的
out1 = conv(x.unsqueeze(-1))
res1 = out1.squeeze(-1)
print(res1.shape)  # (4,256,2048)
print(torch.sum(torch.sum(torch.sum(res1, dim=-1), dim=-1), dim=-1))  # 17060.7676

out2 = conv(x.unsqueeze(-2))
res2 = out2.squeeze(-2)
print(res2.shape)  # (4,256,2048)
print(torch.sum(torch.sum(torch.sum(res2, dim=-1), dim=-1), dim=-1))  # 17060.7676
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值