n = torch.tensor(4)
d = torch.tensor(4)
x = torch.rand(n, 1, d, d)
m = x.view(n, -1).argmax(1)
# since argmax() does only return the index of the flattened
# matrix block we have to calculate the indices by ourself
# by using / and % (// would also work, but as we are dealing with
# type torch.long / works as well
indices = torch.cat(((m / d).view(-1, 1), (m % d).view(-1, 1)), dim=1)
print(x)
print(indices)
def unravel_index(
indices: torch.LongTensor,
shape: Tuple[int, ...],
) -> torch.LongTensor:
r"""Converts flat indices into unraveled coordinates in a target shape.
This is a `torch` implementation of `numpy.unravel_index`.
Args:
indices: A tensor of (flat) indices, (*, N).
shape: The targeted shape, (D,).
Returns:
The unraveled coordinates, (*, N, D).
"""
coord = []
for dim in reversed(shape):
coord.append(indices % dim)
indices = indices // dim
coord = torch.stack(coord[::-1], dim=-1)
return coord
然后,您可以使用torch.argmax函数来获得“展平”Tensor的索引。
y = x.view(20, -1)
indices = torch.argmax(y)
indices.shape # (20,)
用unravel_index函数解出指数。
indices = unravel_index(indices, x.shape[-2:])
indices.shape # (20, 2)
def batch_argmax(tensor, batch_dim=1):
"""
Assumes that dimensions of tensor up to batch_dim are "batch dimensions"
and returns the indices of the max element of each "batch row".
More precisely, returns tensor `a` such that, for each index v of tensor.shape[:batch_dim], a[v] is
the indices of the max element of tensor[v].
"""
if batch_dim >= len(tensor.shape):
raise NoArgMaxIndices()
batch_shape = tensor.shape[:batch_dim]
non_batch_shape = tensor.shape[batch_dim:]
flat_non_batch_size = prod(non_batch_shape)
tensor_with_flat_non_batch_portion = tensor.reshape(*batch_shape, flat_non_batch_size)
dimension_of_indices = len(non_batch_shape)
# We now have each batch row flattened in the last dimension of tensor_with_flat_non_batch_portion,
# so we can invoke its argmax(dim=-1) method. However, that method throws an exception if the tensor
# is empty. We cover that case first.
if tensor_with_flat_non_batch_portion.numel() == 0:
# If empty, either the batch dimensions or the non-batch dimensions are empty
batch_size = prod(batch_shape)
if batch_size == 0: # if batch dimensions are empty
# return empty tensor of appropriate shape
batch_of_unraveled_indices = torch.ones(*batch_shape, dimension_of_indices).long() # 'ones' is irrelevant as it will be empty
else: # non-batch dimensions are empty, so argmax indices are undefined
raise NoArgMaxIndices()
else: # We actually have elements to maximize, so we search for them
indices_of_non_batch_portion = tensor_with_flat_non_batch_portion.argmax(dim=-1)
batch_of_unraveled_indices = unravel_indices(indices_of_non_batch_portion, non_batch_shape)
if dimension_of_indices == 1:
# above function makes each unraveled index of a n-D tensor a n-long tensor
# however indices of 1D tensors are typically represented by scalars, so we squeeze them in this case.
batch_of_unraveled_indices = batch_of_unraveled_indices.squeeze(dim=-1)
return batch_of_unraveled_indices
class NoArgMaxIndices(BaseException):
def __init__(self):
super(NoArgMaxIndices, self).__init__(
"no argmax indices: batch_argmax requires non-batch shape to be non-empty")
以下是测试:
def test_basic():
# a simple array
tensor = torch.tensor([0, 1, 2, 3, 4])
batch_dim = 0
expected = torch.tensor(4)
run_test(tensor, batch_dim, expected)
# making batch_dim = 1 renders the non-batch portion empty and argmax indices undefined
tensor = torch.tensor([0, 1, 2, 3, 4])
batch_dim = 1
check_that_exception_is_thrown(lambda: batch_argmax(tensor, batch_dim), NoArgMaxIndices)
# now a batch of arrays
tensor = torch.tensor([[1, 2, 3], [6, 5, 4]])
batch_dim = 1
expected = torch.tensor([2, 0])
run_test(tensor, batch_dim, expected)
# Now we have an empty batch with non-batch 3-dim arrays' shape (the arrays are actually non-existent)
tensor = torch.ones(0, 3) # 'ones' is irrelevant since this is empty
batch_dim = 1
# empty batch of the right shape: just the batch dimension 0,since indices of arrays are scalar (0D)
expected = torch.ones(0)
run_test(tensor, batch_dim, expected)
# Now we have an empty batch with non-batch matrices' shape (the matrices are actually non-existent)
tensor = torch.ones(0, 3, 2) # 'ones' is irrelevant since this is empty
batch_dim = 1
# empty batch of the right shape: the batch and two dimension for the indices since we have 2D matrices
expected = torch.ones(0, 2)
run_test(tensor, batch_dim, expected)
# a batch of 2D matrices:
tensor = torch.tensor([[[1, 2, 3], [6, 5, 4]], [[2, 3, 1], [4, 5, 6]]])
batch_dim = 1
expected = torch.tensor([[1, 0], [1, 2]]) # coordinates of two 6's, one in each 2D matrix
run_test(tensor, batch_dim, expected)
# same as before, but testing that batch_dim supports negative values
tensor = torch.tensor([[[1, 2, 3], [6, 5, 4]], [[2, 3, 1], [4, 5, 6]]])
batch_dim = -2
expected = torch.tensor([[1, 0], [1, 2]])
run_test(tensor, batch_dim, expected)
# Same data, but a 2-dimensional batch of 1D arrays!
tensor = torch.tensor([[[1, 2, 3], [6, 5, 4]], [[2, 3, 1], [4, 5, 6]]])
batch_dim = 2
expected = torch.tensor([[2, 0], [1, 2]]) # coordinates of 3, 6, 3, and 6
run_test(tensor, batch_dim, expected)
# same as before, but testing that batch_dim supports negative values
tensor = torch.tensor([[[1, 2, 3], [6, 5, 4]], [[2, 3, 1], [4, 5, 6]]])
batch_dim = -1
expected = torch.tensor([[2, 0], [1, 2]])
run_test(tensor, batch_dim, expected)
def run_test(tensor, batch_dim, expected):
actual = batch_argmax(tensor, batch_dim)
print(f"batch_argmax of {tensor} with batch_dim {batch_dim} is\n{actual}\nExpected:\n{expected}")
assert actual.shape == expected.shape
assert actual.eq(expected).all()
def check_that_exception_is_thrown(thunk, exception_type):
if isinstance(exception_type, BaseException):
raise Exception(f"check_that_exception_is_thrown received an exception instance rather than an exception type: "
f"{exception_type}")
try:
thunk()
raise AssertionError(f"Should have thrown {exception_type}")
except exception_type:
pass
except Exception as e:
raise AssertionError(f"Should have thrown {exception_type} but instead threw {e}")
# suppose the tensor is of shape (3,2,2),
>>> a = torch.randn(3, 2, 2)
>>> a
tensor([[[ 0.1450, -1.3480],
[-0.3339, -0.5133]],
[[ 0.6867, -0.2972],
[ 0.8768, 0.0844]],
[[-2.3115, -0.4549],
[-1.5074, -0.8706]]])
# then perform batch-wise max
>>> torch.stack([(a[i]==torch.max(a[i])).nonzero() for i in range(a.size(0))], dim=0)
tensor([[[0, 0]],
[[1, 0]],
[[0, 1]]])
6条答案
按热度按时间iswrvxsc1#
torch.topk()是你正在寻找的。从文件上看,
torch.topk
(input,k,dim=None,largest=True,sorted=True,out=None)-〉(Tensor,LongTensor)返回给定维度沿着给定
input
Tensor的k
最大元素。dim
未给出,则选择输入的最后一个维度。largest
是False
,则返回k个最小元素。sorted
(如果是True
)将确保返回的k个元素本身已排序jyztefdp2#
如果我没理解错的话,你需要的不是值,而是索引。不幸的是,没有开箱即用的解决方案。有一个
argmax()
函数,但我不知道如何让它做你想要的。所以这里有一个小的解决方案,效率也应该是好的,因为我们只是划分Tensor:
n
表示第一维,d
表示最后两个维。我在这里取较小的数字来显示结果。当然,这也适用于n=20
和d=120
:以下是
n=4
和d=4
的输出:我希望这是你想要的!:)
编辑:
这里有一个稍微修改过的,可能会稍微快一点(我猜不会太多:),但它更简单,更漂亮:
而不是像以前那样:
已经对
argmax
值进行了必要的整形:但正如评论中提到的。我认为不可能从中得到更多。
你可以做的一件事,如果它对你来说真的很重要,那就是将上面的函数实现为pytorch的低级扩展(如C++)。
这将给予你一个函数,你可以调用它,并将避免缓慢的Python代码。
https://pytorch.org/tutorials/advanced/cpp_extension.html
kognpnkq3#
下面是
torch
中的unravel_index
实现:然后,您可以使用
torch.argmax
函数来获得“展平”Tensor的索引。用
unravel_index
函数解出指数。vlf7wbxs4#
公认的答案只适用于给定的示例。
tejasvi88的答案很有趣,但无助于回答最初的问题(正如我在那里的评论中所解释的)。
我相信弗朗索瓦的答案是最接近的,因为它处理的是一个更一般的情况(任何数量的维度)。但是,它不与
argmax
连接,并且所示示例没有说明该函数处理批处理的能力。因此,我将在Francois的答案的基础上添加代码来连接到
argmax
。我写了一个新函数batch_argmax
,它返回一个批处理中最大值的索引。批次可以在多个维度中组织。我还提供了一些测试用例以供说明:以下是测试:
qf9go6mv5#
我有一个简单的解决方案,但不是批量计算每个项目的最大值的2D坐标的最佳解决方案。简单的解决方法可能是:
balp4ylt6#
这对我很有效