21-多输入多输出 动手深度学习

#多输入输出通道
import torch
from d2l import torch as d2l

def corr2d_multi_in(x,k):
    return sum(d2l.corr2d(x,k) for x,k in zip(x,k))
x = torch.tensor([[[0.0,1.0,2.0],[3.0,4.0,5.0],[6.0,7.0,8.0]],
                   [[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]])
k = torch.tensor([[[0.0,1.0],[2.0,3.0]],[[1.0,2.0],[3.0,4.0]]])
print(corr2d_multi_in(x,k))
#tensor([[ 56.,  72.],
#        [104., 120.]])

def corr2d_multi_in_out(x,k):
    return torch.stack([corr2d_multi_in(x,k) for k in k],0)
k= torch.stack((k,k+1,k+2),0)
print(k.shape)

print(corr2d_multi_in_out(x,k))
# tensor([[[ 56.,  72.],
#          [104., 120.]],
#
#         [[ 76., 100.],
#          [148., 172.]],
#
#         [[ 96., 128.],
#          [192., 224.]]])

#1*1卷积
def corr2d_multi_in_out_1x1(x,k):
    c_i,h,w = x.shape
    c_o = k.shape[0]
    x = x.reshape((c_i,h*w))
    k = k.reshape((c_o,c_i))
    y = torch.matmul(k,x)
    return y.reshape((c_o,h,w))
x = torch.normal(0,1,(3,3,3))
k = torch.normal(0,1,(2,3,1,1))
y1 = corr2d_multi_in_out_1x1(x,k)
y2 = corr2d_multi_in_out(x,k)
assert float(torch.abs(y1-y2).sum()) < 1e-6
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值