【问题标题】:Expected more than 1 value per channel when training, got input size torch.Size([1, xx])训练时每个通道预期超过 1 个值,得到输入大小 torch.Size([1, xx])
【发布时间】:2020-08-06 15:30:31
【问题描述】:

考虑以下网络sn-p:

def __init__(self, model, n_class, dropout_rate,device):
    super(NewModel, self).__init__()

    self.bert = model
    self.linear = nn.Linear(self.bert.config.hidden_size, 2)
    self.linear_1 = nn.Linear(self.bert.config.hidden_size, self.bert.config.hidden_size)

    self.dropout_rate = dropout_rate
    self.dropout_1 = nn.Dropout(p = self.dropout_rate)

    self.activation = nn.LeakyReLU()

    self.bn = nn.BatchNorm1d(num_features = self.bert.config.hidden_size)

def forward(self, batch):
    outputs = self.bert(
        input_ids = batch[0].to(self.device),
        attention_mask = batch[1].to(self.device),
        token_type_ids = None,
        position_ids = None,
        head_mask = None,
        inputs_embeds = None,
    )

    output = outputs[0]
    pooled_output=output[:,0]
    pooled_output = pooled_output.unsqueeze(0)

    pooled_output_1 = self.dropout_1(self.bn(pooled_output))

    logits = self.linear(F.leaky_relu(self.linear_1(pooled_output_1)))

我的批量大小为 16,在训练期间出现此错误:

ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1, 16])

我已经在DataLoader中设置了drop_last=True,但是错误仍然存​​在。

任何帮助将不胜感激。

【问题讨论】:

    标签: deep-learning neural-network nlp pytorch batch-normalization


    【解决方案1】:

    您的张量尺寸不正确:批量大小应始终排在第一位(以及错误 was got input size torch.Size([1, 16]))。 pytorch 数据加载器加载具有以下形状的数据:(batch_size, input_tensor_size)。因此,input_ids 是你的批次的第一个元素,attention_mask 是第二个元素,我认为这不是你想要的(除非你重新调整数据加载器输出的张量,这将是错误)

    【讨论】:

      【解决方案2】:

      由于您使用的是BatchNorm,并且预计会有batch_dim > 1
      所以请在测试期间通过输入之前model.eval()

      【讨论】:

        猜你喜欢
        • 2021-07-31
        • 1970-01-01
        • 2021-05-10
        • 2022-12-22
        • 2022-06-10
        • 1970-01-01
        • 2021-03-11
        • 2021-04-19
        • 2021-12-26
        相关资源
        最近更新 更多