Valueerror异常:使用一个目标的大小(火炬。大小([2,1])),这是不同于输入的大小(火炬。大小([16,1]))被弃用

0

的问题

我在试图建立一个模型,用于表问题对数据集输出是二进制的1或0,但是我得到这一错误。 我知道的输出形状的我的模型是不同的输入的形状,但我不知道怎么修它。 批的大小设置为16

    class Bert_model (nn.Module):
      def __init__(self) :
        super(Bert_model,self).__init__()
        self.bert =  BertModel.from_pretrained('bert-base-uncased', return_dict=False)
        self.drop_layer = nn.Dropout(.25)
        self.output = nn.Linear(self.bert.config.hidden_size,1)
    
      def forward(self,input_ids,attention_mask):
        _,o2 = self.bert (input_ids =input_ids , attention_mask = attention_mask )
        o2 = self.drop_layer(o2)
        return self.output(o2)

    model = Bert_model()
    
    loss_fn = nn.BCELoss().to(device)

    def train_epoch(
      model, 
      data_loader, 
      loss_fn, 
      optimizer, 
      device, 
      n_examples
    ):
      model = model.train()
    
      losses = []
      correct_predictions = 0
      
      for d in data_loader:
        input_ids = d["input_ids"].to(device)
        attention_mask = d["attention_mask"].to(device)
        targets = d["target"].to(device)
    
        input_ids = input_ids.view(BATCH_SIZE,-1)
        attention_mask = attention_mask.view(BATCH_SIZE,-1)
    
        outputs = model(
          input_ids=input_ids,
          attention_mask=attention_mask
        )
    
        _, preds = torch.max(outputs, dim=1)
    
        targets = targets.unsqueeze(-1)
        loss = loss_fn(F.softmax(outputs,dim=1), targets)
    
        correct_predictions += torch.sum(preds == targets)
        losses.append(loss.item())
    
        loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
        optimizer.step()
        optimizer.zero_grad()
    
      return correct_predictions.double() / n_examples, np.mean(losses)

错误:

/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py in
binary_cross_entropy(input, target, weight, size_average, reduce,
reduction)    2913         weight = weight.expand(new_size)    2914 
-> 2915     return torch._C._nn.binary_cross_entropy(input, target, weight, reduction_enum)    2916     2917  ValueError: Using a target
size (torch.Size([2, 1])) that is different to the input size
(torch.Size([16, 1])) is deprecated
deep-learning pytorch
2021-11-21 11:25:25
1

最好的答案

0

从栈跟踪,错误发生在BCELoss计算,这是由于事实 outputs.shape(16, 1)同时 targets.shape(2, 1).

我看到一个主要问题在于你的码: BCELoss 用于比较的概率分布(检查 文件),而模型输出具的形状 (n, 1) 哪里 n 是批的大小(在你的情况16条)。 事实上,在返回的声明 forward 你通过 o2 线性层,其输出形状 1.

问题对数据集 是为二进制分类的任务,所以你需要把你的输出成概率分布,例如,通过使用 Sigmoid 或者设置的线性层的输出大于2,并且然后使用softmax.

2021-11-21 15:50:29

此外,您可以开关 BCELossCrossEntropyLoss,它是二进制分类的问题。
aretor

我改变的损失功能(BCEWithLogitsLoss)适用乙状结肠的输出,然后我删除了softmax. 问题仍然存在,但现在因为目标的大小(10,1)和不同的输入的(16,1)
BuzzedHub

这是很难告诉错误,从你的代码。 鉴于16个是正确的批大小,仔细检查当你的目标尺寸变化从16到10个。 请避免改变你的身体问题,否则答案将是没有意义了。
aretor

其他语言

此页面有其他语言版本

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................