首页 > 解决方案 > BertForNextSentencePrediction - 将 logits 转换为布尔值?

问题描述

我正在尝试使用在 BERT 中预训练的 Next Sentence Prediction 模型。

我在课堂上使用示例TFBertForNextSequencePrediction。我知道 seq_relationship_score 返回的 logits 指出下一个句子是否属于先前的上下文。我尝试使用 keras 的 Softmax,但它没有返回布尔值。

import tensorflow as tf
from transformers import BertTokenizer, TFBertForNextSentencePrediction

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = TFBertForNextSentencePrediction.from_pretrained('bert-base-uncased')

input_ids = tf.constant(tokenizer.encode(["My dog is called Tetley.", "My dog is my best friend"], add_special_tokens=True))[None, :]  # Batch size 1

outputs = model(input_ids)
seq_relationship_scores = outputs[0]

print(seq_relationship_scores)

import keras
print(keras.activations.softmax(seq_relationship_scores, axis=-1))

如何测试两个句子是否与 seq_relationship_scores 具有相同的上下文?

https://huggingface.co/transformers/_modules/transformers/modeling_tf_bert.html#TFBertForNextSentencePrediction 这个模型是一个tf.keras.Model <https://www.tensorflow.org/api_docs/python/tf/keras/Model>__子类。将其用作常规 TF 2.0 Keras 模型,并参阅 TF 2.0 文档以了解与一般使用和行为相关的所有事项。

输出看起来像这样:

tf.Tensor([[ 4.642335  -3.4926772]], shape=(1, 2), dtype=float32)
Using TensorFlow backend.
tf.Tensor([[9.9970692e-01 2.9300974e-04]], shape=(1, 2), dtype=float32)

标签: pythontensorflowkeras

解决方案


反转 logits 以获取概率。然后对概率进行反向排序以获得最近的句子。您无需在此处使用 softmax,因为您正在查看相似性。


推荐阅读