MRC中答案预测实现(numpy、torch、tensorflow)


import tensorflow as tf
import numpy as np
import torch

def answer_interval_numpy(prob_s, prob_e, answer_max_len=None):
    """

    :param prob_s:  shape=[seq_len]
    :param prob_e:  shape= [seq_len]
    :param answer_max_len:  int,
    :return:
    """

    answer_probs = np.matmul(prob_s, np.transpose(prob_e, axes=-1))  # dtype: np.array
    if answer_max_len is not None:
        answer_probs = np.tril(np.triu(answer_probs, k=0), k=answer_max_len-1)

    best_start, best_end = np.unravel_index(np.argmax(answer_probs), answer_probs.shape)
    return best_start, best_end



def answer_interval_torch(prob_s, prob_e, max_answer_len=None):
    # 设文本共m个词,prob_s是大小为m的开始位置概率,prob_e是大小为m的结束位置概率,均为一维PyTorch张量
    # L为答案区间可以包含的最大的单词数
    # 输出为概率最高的区间在文本中的开始和结束位置
    # 获得m×m的矩阵,其中prob[i,j]=prob_s[i]×prob_e[j]
    prob = torch.ger(prob_s, prob_e)
    # 将prob限定为上三角矩阵,且只保留主对角线及其右上方L-1条对角线的值,其他值清零
    if max_answer_len is not None:
        # 即如果i>j或j-i+1>L,设置prob[i, j] = 0
        prob.triu_().tril_(max_answer_len - 1)
    # 转化成为numpy数组
    prob = prob.numpy()
    # 获得概率最高的答案区间,开始位置为第best_start个词, 结束位置为第best_end个词
    best_start, best_end = np.unravel_index(np.argmax(prob), prob.shape)
    return best_start, best_end


def answer_interval_tf(prob_s, prob_e, max_answer_len=None):
    """

    :param prob_s: [seq_len]
    :param prob_e:  [seq_len]
    :param max_answer_len:
    :return:
    """

    answer_probs = tf.matmul(prob_s, prob_e, transpose_b=True)
    answer_triu = tf.experimental.numpy.triu(answer_probs, k=0)
    if max_answer_len is not None:
        answer_triu = tf.experimental.numpy.tril(answer_triu, k=max_answer_len-1)

    indices = tf.unravel_index(tf.argmax(answer_triu), answer_triu.shape)
    return indices

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值