为卷积层的特征图分配权重[关闭]

扎眼的阳光 pytorch 188

原文标题Assigning weights to the feature maps of a convolutional layer [closed]

我在使用一个类SE_Block(挤压和激励块),并给出一个卷积层的N特征图(通道)作为这个SE_Block的输入。我的目标是使用SE_Block后,它的每个输入特征图都获得自己的权重。换句话说,SE_Block旨在为每个特征图分配权重。但我面临以下错误:

TypeError:init() 缺少 1 个必需的位置参数:’c’

class SE_Block(nn.Module):
"credits: https://github.com/moskomule/senet.pytorch/blob/master/senet/se_module.py#L4"
def __init__(self, c, r=16):
    super().__init__()
    self.squeeze = nn.AdaptiveAvgPool2d(1)
    self.excitation = nn.Sequential(
        nn.Linear(c, c // r, bias=False),
        nn.ReLU(inplace=True),
        nn.Linear(c // r, c, bias=False),
        nn.Sigmoid()
    )

def forward(self, x):
    bs, c, _, _ = x.shape
    y = self.squeeze(x).view(bs, c)
    y = self.excitation(y).view(bs, c, 1, 1)
    return x * y.expand_as(x)

我的代码:

class myclass(nn.Module):
def __init__(self, in_channel=1024, out_channel=[512], out_sigmoid=False):
    super(myclass, self).__init__()
    
    self.out_sigmoid=out_sigmoid
    
    self.SEBlock = SE_Block()

    self.deconvlayer = self._make_deconv(in_channel, out_channel[0], num_conv=3)
    self.upsample=Upsample(scale_factor=2, mode='bilinear')
    
 
def _make_deconv(self, in_channel, out_channel, num_conv=2, kernel_size=3, stride=1, padding=1):
    layers=[]
    layers.append(BasicConv2d(in_channel, out_channel ,kernel_size=kernel_size, stride=stride, padding=padding))
    for i in range(1, num_conv):
        layers.append(_SepConv2d(out_channel, out_channel,kernel_size=kernel_size, stride=stride, padding=padding))
    
    return nn.Sequential(*layers)

def forward(self, x):
    x=self.deconvlayer(x)
    x = self.upsample(x)
    w = self.SEBlock(x)
    
    return x, w

原文链接:https://stackoverflow.com//questions/71935848/assigning-weights-to-the-feature-maps-of-a-convolutional-layer

回复

我来回复
  • freerafiki的头像
    freerafiki 评论

    好吧,正如错误所说,__init__缺少c参数。

    当你初始化你的 SE_block 时,构造函数内的__init__方法将被调用,所以当这行被执行时:

    self.SEBlock = SE_Block()

    而且您没有传递任何参数,但是当您定义它时,您是在告诉他期望 c 参数

    def __init__(self, c, r=16):

    这就是为什么当__init__运行时会引发错误。要解决错误,您可以:

    • 使用 def __init__(self, c=16, r=16): 或您想要的其他数字使 c 成为可选的(就像您对 r 所做的那样)
    • 初始化时传递 c ,使用 self.SEBlock = SE_Block(c=16) 或任何你想要的数字。
    2年前 0条评论
  • Deusy94的头像
    Deusy94 评论

    当您创建 SE_block 时,您没有传递 c(通道)参数。您需要添加:

    class myclass(nn.Module):
        def __init__(self, in_channel=1024, out_channel=512, out_sigmoid=False):
    
            ...
    
            self.SEBlock = SE_Block(out_channel)   # Adding argument here
    
            ...
    

    您的类实现中的前向部分也有一些错误,应将其重写为:

    class myclass(nn.Module):
    
        ...
    
        def forward(self, x):
            x = self.deconvlayer(x)  # Remove the 5_5 part
            x = self.upsample(x)     # Remove the 5_5 part
            w = self.SEBlock(x)
        
            return x, w
    
    2年前 0条评论