打赏

多输入多输出通道——pytorch版

import torch
from d2l import torch as d2l
from torch import nn

# 多输入通道互相关运算
def corr2d_multi_in(x,k):
    # zip对每个通道配对,返回一个可迭代对象,其中每个元素是一个(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]]
])

corr2d_multi_in(X, K)

# 计算多个通道的输出的互相关函数
def corr2d_multi_in_out(x,K):
    # x是3维,K是四维,遍历K得到三维,与x做运算,得到二维的矩阵
    # 新建一个维度0 ,把矩阵堆起来
    return torch.stack([corr2d_multi_in(x,k) for k in K],0)

K = torch.stack((K,K+1,K+2),0)
# 输入通道是3 输入是2 高和宽是2
print(K.shape)
print(K)
# 三个卷积核,每个卷积核有两个通道,每个通道是2*2的矩阵
corr2d_multi_in_out(X,K)
print(X.shape)
# 1x1卷积
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))
    print('X是',X)
    K=K.reshape((c_o,c_i))
    print('K是',K)
    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))
print('X是',X)
print('K是',K)
# Y1算卷积 Y2算全连接
Y1 = corr2d_multi_in_out_1x1(X,K)
Y2 = corr2d_multi_in_out(X,K)
assert float(torch.abs(Y1-Y2).sum())<1e-6


# 将高度和宽度的步幅设置为2
conv2d = nn.Conv2d(1,1,kernel_size=3,padding=1,stride=2)
def comp_conv2d(conv2d,x):
    # 在维度前面加上通道数和批量大小数1
    x=x.reshape((1,1)+x.shape)
    # 得到4维
    y=conv2d(x)
    # 把前面两维去掉
    return y.reshape(y.shape[2:])

comp_conv2d(conv2d,X).shape
# torch.size([4,4])

 

posted @ 2023-08-06 14:33  不像话  阅读(45)  评论(0编辑  收藏  举报