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
10-18
1041
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-24
364
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-30
1555
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-26
6343
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-11
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-19
5171
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-21
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交