python - pytorch Argmax 冲突时的索引选择
问题描述
我一直在尝试学习张量运算,而这个让我陷入了困境。
假设我有一个张量 t:
t = torch.tensor([
[1,0,0,2],
[0,3,3,0],
[4,0,0,5]
], dtype = torch.float32)
现在这是一个等级 2 的张量,我们可以为每个等级/维度应用 argmax。假设我们将它应用于 dim = 1
t.max(dim = 1)
(tensor([2., 3., 5.]), tensor([3, 2, 3]))
现在我们可以看到结果与预期的一样,沿 dim =1 的张量有 2,3 和 5 作为最大元素。但是在 3 上有一个冲突。有两个值完全相似。
它是如何解决的?是随意选择的吗?是否有选择像LR,更高的索引值的顺序?
我将不胜感激有关如何解决此问题的任何见解!
解决方案
这是一个很好的问题,我自己偶然发现了几次。最简单的答案是,不能保证torch.argmax
(或torch.max(x, dim=k)
,在指定 dim 时也返回索引)将始终返回相同的索引。相反,它将返回任何有效索引到 argmax 值,可能是随机的。正如官方论坛中的这个线程所讨论的,这被认为是期望的行为。(我知道我不久前读过的另一个线程使这一点更加明确,但我再也找不到它了)。
话虽如此,由于这种行为对我的用例来说是不可接受的,所以我编写了以下函数来查找最左边和最右边的索引(请注意,这condition
是您传入的函数对象):
def __consistent_args(input, condition, indices):
assert len(input.shape) == 2, 'only works for batch x dim tensors along the dim axis'
mask = condition(input).float() * indices.unsqueeze(0).expand_as(input)
return torch.argmax(mask, dim=1)
def consistent_find_leftmost(input, condition):
indices = torch.arange(input.size(1), 0, -1, dtype=torch.float, device=input.device)
return __consistent_args(input, condition, indices)
def consistent_find_rightmost(input, condition):
indices = torch.arange(0, input.size(1), 1, dtype=torch.float, device=input.device)
return __consistent_args(input, condition, indices)
# one example:
consistent_find_leftmost(torch.arange(10).unsqueeze(0), lambda x: x>5)
# will return:
# tensor([6])
希望他们会有所帮助!(哦,如果您有更好的实现,请告诉我)
推荐阅读
- flutter - 缩放后平移不在同一位置?
- javascript - 固定按钮 ReactJS
- android - RecyclerView 输出值到 textview
- python - 在 django 中创建相关对象
- python - 将 csv 转换为 json 时,.append() 函数中的 KeyError
- java - 如何从 wsdl 和额外的 xsd:s 生成带有 jaxws-maven-plugin 的 java 客户端?
- git - git branch -v 总是卡在cmd
- javascript - 我们如何将 javascript 数组修改为数组对象?
- jquery-select2 - 在 EasyAdmin 中检测 Select2 的 onChange 事件
- php - MySQL COUNT 不返回正确的值