【问题标题】:Pytorch CNN:RuntimeError: Given groups=1, weight of size [16, 16, 3], expected input[500, 1, 19357] to have 16 channels, but got 1 channels insteadPytorch CNN:RuntimeError: 给定组=1,大小为 [16, 16, 3] 的权重,预期输入 [500, 1, 19357] 有 16 个通道,但有 1 个通道
【发布时间】:2020-11-23 16:06:38
【问题描述】:
class ConvolutionalNetwork(nn.Module):
    def __init__(self, in_features, trial):
        super().__init__()
        self.in_features = in_features
        self.trial = trial
        # this computes num features outputted from the two conv layers
        c1 = int(((self.in_features - 2)) / 64)  # this is to account for the loss due to conversion to int type
        c2 = int((c1 - 2) / 64)
        self.n_conv = int(c2 * 16)
        # self.n_conv = int((( ( (self.in_features - 2)/4 ) - 2 )/4 ) * 16)
        self.conv1 = nn.Conv1d(16, 16, 3, 1)
        self.conv1_bn = nn.BatchNorm1d(16)
        self.conv2 = nn.Conv1d(16, 16, 3, 1)
        self.conv2_bn = nn.BatchNorm1d(16)
        # self.dp = nn.Dropout(trial.suggest_uniform('dropout_rate',0,1.0))
        self.dp = nn.Dropout(0.5)
        self.fc3 = nn.Linear(self.n_conv, 2)

    def forward(self, x):
        # shape x for conv 1d op
        x = x.view(-1, 1, self.in_features)
        x = self.conv1(x)
        x = F.tanh(x)
        x = F.max_pool1d(x, 64, 64)
        x = self.conv2(x)
        x = F.tanh(x)
        x = F.max_pool1d(x, 64, 64)
        x = x.view(-1, self.n_conv)

        x = self.dp(x)
        x = self.fc3(x)
        x = F.log_softmax(x, dim=1)

        return x

运行上面的代码,弹出这个错误:

RuntimeError: Given groups=1, weight of size [16, 16, 3], expected input[500, 1, 19357] to have 16 channels, but got 1 channels instead.

任何人都可以就此提出建议?它说输入有差异,但上面的代码在早期运行良好,不确定我重新排列代码后发生了什么。

【问题讨论】:

    标签: pytorch conv-neural-network


    【解决方案1】:

    好吧,在输入 forward 方法之后,您正在重塑您的输入数组,使其只有一个通道:

    x = x.view(-1, 1, self.in_features)
    

    同时在模型构造函数中指定 conv1 有 16 个通道作为输入:

    self.conv1 = nn.Conv1d(16, 16, 3, 1)
    

    因此预期 16 个频道但收到 1 个的错误。

    这里有两点需要注意:

    • 如果你习惯了 tensorflow,也许你认为通道是最后一维,但在 pytorch 中,通道位于第一维。看看Conv1d torch documentation。在重塑数据时要考虑到这一点。
    • Conv1d 与您输入的长度无关(我告诉您这一点是为了防止 in_features 表示长度)

    我无法为您提供具体的解决方案,因为我不确定您要做什么。

    【讨论】:

      猜你喜欢
      • 2020-10-06
      • 2021-04-19
      • 2020-03-17
      • 2020-01-27
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 2019-04-24
      相关资源
      最近更新 更多