我微调了用于句子分类的预训练 BERT,但我无法让它预测新句子

kay*_*esh 1 python nlp machine-learning pytorch huggingface-transformers

下面是我微调的结果。

Training Loss   Valid. Loss Valid. Accur.   Training Time   Validation Time
epoch                   
1   0.16    0.11    0.96    0:02:11 0:00:05
2   0.07    0.13    0.96    0:02:19 0:00:05
3   0.03    0.14    0.97    0:02:22 0:00:05
4   0.02    0.16    0.96    0:02:21 0:00:05
Run Code Online (Sandbox Code Playgroud)

接下来我尝试使用该模型来预测 csv 文件中的标签。我创建了一个标签列,将类型设置为 int64 并运行预测。

print('Predicting labels for {:,} test sentences...'.format(len(input_ids)))
model.eval()
# Tracking variables 
predictions , true_labels = [], []
# Predict 
for batch in prediction_dataloader:
  # Add batch to GPU
  batch = tuple(t.to(device) for t in batch)

  # Unpack the inputs from our dataloader
  b_input_ids, b_input_mask, b_labels = batch

  # Telling the model not to compute or store gradients, saving memory and 
  # speeding up prediction
  with torch.no_grad():
      # Forward pass, calculate logit predictions
      outputs = model(b_input_ids, token_type_ids=None, 
                      attention_mask=b_input_mask)

  logits = outputs[0]

  # Move logits and labels to CPU
  logits = logits.detach().cpu().numpy()
  label_ids = b_labels.to('cpu').numpy()

  # Store predictions and true labels
  predictions.append(logits)
  true_labels.append(label_ids)


Run Code Online (Sandbox Code Playgroud)

然而,虽然我能够打印出预测[4.235,-4.805]等,以及true_labels[NaN,NaN.....],但我无法实际获得预测标签{0或1}。我在这里错过了什么吗?

Jin*_*ich 6

模型的输出是logits,即使用softmax 归一化之前的概率分布。

如果你获取输出:[4.235, -4.805]并对其运行 softmax

In [1]: import torch
In [2]: import torch.nn.functional as F 
In [3]: F.softmax(torch.tensor([4.235, -4.805]))
Out[3]: tensor([9.9988e-01, 1.1856e-04])
Run Code Online (Sandbox Code Playgroud)

您获得标签 0 的概率分数为 99%。当您将 logits 作为 2D 张量时,您可以通过调用轻松获得类别

logits.argmax(0)
Run Code Online (Sandbox Code Playgroud)

NaN您中的 s 值可能true_labels是您加载数据方式的错误,它与 BERT 模型无关。