【问题标题】:I fine tuned a pre-trained BERT for sentence classification, but i cant get it to predict for new sentences我微调了一个用于句子分类的预训练 BERT,但我无法让它预测新句子
【发布时间】:2020-07-10 09:28:29
【问题描述】:

以下是我微调的结果。

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

接下来我尝试使用该模型从 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)


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

【问题讨论】:

    标签: python machine-learning nlp pytorch huggingface-transformers


    【解决方案1】:

    模型的输出是 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])
    

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

    logits.argmax(0)
    

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

    【讨论】:

    • 现在这很有趣。这就是我的数据被加载的方式。
    • 现在这很有趣。这就是我的数据被加载的方式。 df = pd.read_csv("/content/t_test.csv", sep=',', encoding='latin_1', header = None, names=['sentenceID', 'sentence', 'label'])。标签列是空的,也许熊猫默认用 NaN 填充它。我做错了吗?
    • 用户警告:softmax 的隐式维度选择已被弃用。更改调用以包含 dim=X 作为参数。当我打电话给 F.softmax 时,我收到了这个警告。但是,我发现这条线没有错误。 1. logits=output[0] 2. probs = softmax(outputs[0], dim=1)
    • ad NaN:是的,就是这样。那么,您没有标签,为什么还要尝试加载它们呢?
    • 我加载它们是为了让我的模型对句子进行预测。我计划将句子以及新预测的标签一起提交给第三方以验证准确性。所以这就是原因。
    猜你喜欢
    • 2019-07-07
    • 2021-06-30
    • 2020-03-29
    • 1970-01-01
    • 2020-06-18
    • 2021-02-16
    • 1970-01-01
    • 2021-08-12
    • 2020-01-31
    相关资源
    最近更新 更多