如何使用线性层卷积2d图像,张量深度3?(在PyTorch中)

2024-09-30 12:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个张量形状(3,256,256)。 我想通过卷积或循环通过它逐像素返回我一个张量形状(1,256,256)

这听起来可能有点混乱,所以这是我到现在为止的代码,所以你知道我的意思

class MorphNetwork(nn.Module):
    def __init__(self):
        super().__init__()

        self.fc1 = nn.Linear(3, 8)
        self.fc2 = nn.Linear(8, 1)

    def forward(self, x):
        # The input here is shape (3, 256, 256)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        # Returned shape should be (1, 256, 256)
        return x

正如你所看到的,我的线性层接受的形状3与我的原始张量的深度相匹配。在所有256x256中循环以返回张量形状(1256256)的最佳方式是什么


Tags: 代码selfinitdef像素nn卷积class
1条回答
网友
1楼 · 发布于 2024-09-30 12:22:06

采用3dim输入和8dim输出的线性层在数学上相当于具有1x1空间大小内核的卷积(我强烈建议您实际“进行数学运算”,并说服自己这确实是正确的)

因此,可以使用以下模型,将线性层替换为^{}

class MorphNetwork(nn.Module):
    def __init__(self):
        super().__init__()

        self.c1 = nn.Conv2d(3, 8, kernel_size=1, bias=True)
        self.c2 = nn.Conv2d(8, 1, kernel_size=1, bias=True)

    def forward(self, x):
        # The input here is shape (3, 256, 256)
        x = F.relu(self.c1(x))
        x = self.c2(x)
        # Returned shape should be (1, 256, 256)
        return x

如果您坚持使用nn.Linear层,您可以^{}您的输入,然后^{}在应用线性层后将其恢复

相关问题 更多 >

    热门问题