python - 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)
解决方案
反转 logits 以获取概率。然后对概率进行反向排序以获得最近的句子。您无需在此处使用 softmax,因为您正在查看相似性。
推荐阅读
- python - 从反应到烧瓶的发布请求
- ios - 将数据传递给 VNCoreMLRequest
- pytorch - 为什么更新叶子张量时没有梯度
- sql - 如何调整TDengine数据库中的参数?
- configuration - 如何根据 travis 中的某些条件进行部署?
- asp.net-core - IdentityServer4 ADFS 外部不返回角色
- mysql - 创建唯一索引时“外键约束形成错误”
- angular - 是否有任何解决方案可以将此服务用于 Angular 10 中的下拉列表?
- kotlin-multiplatform - 如何在 Multiplatform Ktor 和 Coil 之间共享 HttpClient?
- dart - 在一个语句中两次访问同一个 getter 的性能