bert输出的概率值

bert 的tensorflow 版本做 do_predict=TRUE 时 会产生一个文件 test_results.tsv,数据大概是

img

也就是每一个句子都生成了一个概率值,这个概率值具体指的是哪种概率呢?如果我想做双文本的相似度计算,这个概率可以进行使用吗?

这个 test_results.tsv 文件中的数据表示了每个输入样本在每个类别上的概率。在你提供的数据中,有两列,因此我猜测你的模型是一个二分类问题。第一列表示属于类别 0 的概率,第二列表示属于类别 1 的概率。这些概率之和应该等于 1。

关于你的问题:这个概率值能否用于双文本的相似度计算,取决于你的训练数据和标签。如果你的训练数据包含成对的文本,并且标签表示这两个文本之间的相似度(例如,类别 0 表示不相似,类别 1 表示相似),那么这个概率可以用于衡量双文本相似度。

在这种情况下,你可以使用类别 1(即第二列)的概率作为相似度分数。这个概率表示了模型预测两个输入文本相似的程度。较高的概率值表示文本更相似,而较低的概率值表示文本不相似。

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 以下回答来自chatgpt:

    回答:

    Bert模型的输出是一组概率值,通常是用来表示输入文本序列在不同类别或标签上的概率分布。例如,在文本分类中,每个类别都会对应一个概率值来表示该文本属于该类别的概率有多大。对于双文本相似度计算,可以将两个文本的Bert输出的概率向量用余弦相似度或其他相似度度量方法进行比较,这样可以得到两个文本的相似度得分。

    代码示例:

    import tensorflow as tf
    import numpy as np
    
    # 加载Bert模型和vocab文件
    bert_model_dir = 'path/to/bert/model/dir'
    vocab_file = 'path/to/vocab/file'
    tokenizer = tokenization.FullTokenizer(vocab_file=vocab_file, do_lower_case=True)
    bert_config = modeling.BertConfig.from_json_file(os.path.join(bert_model_dir, 'bert_config.json'))
    
    # 定义输入数据
    input_ids = tf.placeholder(tf.int32, shape=[None, bert_config.max_position_embeddings], name='input_ids')
    input_mask = tf.placeholder(tf.int32, shape=[None, bert_config.max_position_embeddings], name='input_mask')
    segment_ids = tf.placeholder(tf.int32, shape=[None, bert_config.max_position_embeddings], name='segment_ids')
    
    # 构建Bert模型
    model = modeling.BertModel(config=bert_config, is_training=False, input_ids=input_ids,
                               input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=False)
    
    # 获取序列对的Bert输出向量
    output_layer = model.get_pooled_output()
    
    # 加载测试数据集
    test_examples = []
    for line in open('path/to/test/data', 'r', encoding='utf-8'):
        line = line.strip()
        if not line:
            continue
        parts = line.split('\t')
        if len(parts) != 2:
            continue
        example = InputExample(guid=None, text_a=parts[0], text_b=parts[1], label=None)
        test_examples.append(example)
    
    # 将测试数据集转化为特征
    test_features = convert_examples_to_features(
        test_examples, label_list=None, max_seq_length=128, tokenizer=tokenizer)
    
    # 定义测试函数
    def test(sess):
        output_file = 'path/to/test/output/file'
        with open(output_file, 'w', encoding='utf-8') as fout:
            for feature in test_features:
                feed_dict = {input_ids: [feature.input_ids], input_mask: [feature.input_mask],
                             segment_ids: [feature.segment_ids]}
                output = sess.run(output_layer, feed_dict=feed_dict)
                output_line = '\t'.join([str(x) for x in output[0]]) + '\n'
                fout.write(output_line)
    
    # 对测试集进行预测
    with tf.Session() as sess:
        saver = tf.train.Saver()
        saver.restore(sess, tf.train.latest_checkpoint(bert_model_dir))
        test(sess)
    
    # 计算余弦相似度
    def cosine_sim(v1, v2):
        return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
    
    # 加载输出文件
    test_results_file = 'path/to/test/results/file'
    test_results = []
    for line in open(test_results_file, 'r', encoding='utf-8'):
        line = line.strip()
        if not line:
            continue
        parts = line.split('\t')
        if len(parts) != 768:
            continue
        vec = np.array([float(x) for x in parts])
        test_results.append(vec)
    
    # 进行双文本相似度计算
    sim_matrix = np.zeros((len(test_examples), len(test_examples)))
    for i in range(len(test_examples)):
        for j in range(len(test_examples)):
            vec1 = test_results[i]
            vec2 = test_results[j]
            sim = cosine_sim(vec1, vec2)
            sim_matrix[i][j] = sim
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^