Python 多维张量的topk指数
我有一个二维张量,我想得到顶k值的指数。我知道函数。pytorch的topk函数的问题是,它计算某个维度上的topk值。我想得到两个维度上的topk值 例如,对于下列张量 a=火炬张量[[4,9,7,4,0], [8, 1, 3, 1, 0], [9, 8, 4, 4, 8], [0, 9, 4, 7, 8], [8, 8, 0, 1, 4]] pytorch的topk函数将提供以下信息 数值,指数=torch.topka,3 印刷索引 张量[[1,2,0], [0, 2, 1], [0, 1, 4], [1, 4, 3], [1, 0, 4]] 但我想得到以下信息Python 多维张量的topk指数,python,pytorch,tensor,matrix-indexing,Python,Pytorch,Tensor,Matrix Indexing,我有一个二维张量,我想得到顶k值的指数。我知道函数。pytorch的topk函数的问题是,它计算某个维度上的topk值。我想得到两个维度上的topk值 例如,对于下列张量 a=火炬张量[[4,9,7,4,0], [8, 1, 3, 1, 0], [9, 8, 4, 4, 8], [0, 9, 4, 7, 8], [8, 8, 0, 1, 4]] pytorch的topk函数将提供以下信息 数值,指数=torch.topka,3 印刷索引 张量[[1,2,0], [0, 2, 1], [0, 1,
tensor([[0, 1],
[2, 0],
[3, 1]])
这是2D张量中9的指数
有什么方法可以使用pytorch实现这一点吗?您可以展平原始张量,应用topk,然后使用以下方法将合成的标量索引转换回多维索引:
def descalarization(idx, shape):
res = []
N = np.prod(shape)
for n in shape:
N //= n
res.append(idx // N)
idx %= N
return tuple(res)
例如:
torch.tensor([descalarization(k, a.size()) for k in torch.topk(a.flatten(), 5).indices])
# Returns
# tensor([[3, 1],
# [2, 0],
# [0, 1],
# [3, 4],
# [2, 4]])
您可以展平原始张量,应用topk,然后使用以下方法将结果标量索引转换回多维索引:
def descalarization(idx, shape):
res = []
N = np.prod(shape)
for n in shape:
N //= n
res.append(idx // N)
idx %= N
return tuple(res)
例如:
torch.tensor([descalarization(k, a.size()) for k in torch.topk(a.flatten(), 5).indices])
# Returns
# tensor([[3, 1],
# [2, 0],
# [0, 1],
# [3, 4],
# [2, 4]])
输出:
[[3 1]
[2 0]
[0 1]]
展平并找到顶部k
使用展开索引将一维索引转换为二维索引
输出:
[[3 1]
[2 0]
[0 1]]
展平并找到顶部k
使用展开索引将一维索引转换为二维索引
您可以根据需要进行一些向量运算以进行过滤。在这种情况下,不要使用topk
print(a)
tensor([[4, 9, 7, 4, 0],
[8, 1, 3, 1, 0],
[9, 8, 4, 4, 8],
[0, 9, 4, 7, 8],
[8, 8, 0, 1, 4]])
values, indices = torch.max(a,1) # get max values, indices
temp= torch.zeros_like(values) # temporary
temp[values==9]=1 # fill temp where values are 9 (wished value)
seq=torch.arange(values.shape[0]) # create a helper sequence
new_seq=seq[temp>0] # filter sequence where values are 9
new_temp=indices[new_seq] # filter indices with sequence where values are 9
final = torch.stack([new_seq, new_temp], dim=1) # stack both to get result
print(final)
tensor([[0, 1],
[2, 0],
[3, 1]])
您可以根据需要进行一些向量运算以进行过滤。在这种情况下,不要使用topk
print(a)
tensor([[4, 9, 7, 4, 0],
[8, 1, 3, 1, 0],
[9, 8, 4, 4, 8],
[0, 9, 4, 7, 8],
[8, 8, 0, 1, 4]])
values, indices = torch.max(a,1) # get max values, indices
temp= torch.zeros_like(values) # temporary
temp[values==9]=1 # fill temp where values are 9 (wished value)
seq=torch.arange(values.shape[0]) # create a helper sequence
new_seq=seq[temp>0] # filter sequence where values are 9
new_temp=indices[new_seq] # filter indices with sequence where values are 9
final = torch.stack([new_seq, new_temp], dim=1) # stack both to get result
print(final)
tensor([[0, 1],
[2, 0],
[3, 1]])
你只是想要例子中的前1名,还是你也对topk感兴趣?你只是想要例子中的前1名,还是你也对topk感兴趣?