多个维度上的 PyTorch torch.max [英] PyTorch torch.max over multiple dimensions

查看:38
本文介绍了多个维度上的 PyTorch torch.max的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这样的张量:x.shape = [3, 2, 2].

import torch

x = torch.tensor([
    [[-0.3000, -0.2926],[-0.2705, -0.2632]],
    [[-0.1821, -0.1747],[-0.1526, -0.1453]],
    [[-0.0642, -0.0568],[-0.0347, -0.0274]]
])

我需要在第二和第三维度上使用 .max().我希望像这样的 [-0.2632, -0.1453, -0.0274] 作为输出.我尝试使用:x.max(dim=(1,2)),但这会导致错误.

I need to take .max() over the 2nd and 3rd dimensions. I expect some like this [-0.2632, -0.1453, -0.0274] as output. I tried to use: x.max(dim=(1,2)), but this causes an error.

推荐答案

现在,您可以这样做了.PR 已合并(8 月 28 日),现在可以在每晚发布.

Now, you can do this. The PR was merged (Aug 28) and it is now available in the nightly release.

只需使用 torch.amax():

Simply use torch.amax():

import torch

x = torch.tensor([
    [[-0.3000, -0.2926],[-0.2705, -0.2632]],
    [[-0.1821, -0.1747],[-0.1526, -0.1453]],
    [[-0.0642, -0.0568],[-0.0347, -0.0274]]
])

print(torch.amax(x, dim=(1, 2)))

# Output:
# >>> tensor([-0.2632, -0.1453, -0.0274])


原答案

截至今天(2020 年 4 月 11 日),在 PyTorch 中无法在多个维度上执行 .min().max().有一个关于它的未决问题,你可以关注它,看看它是否得到了实施.您的情况的解决方法是:

As of today (April 11, 2020), there is no way to do .min() or .max() over multiple dimensions in PyTorch. There is an open issue about it that you can follow and see if it ever gets implemented. A workaround in your case would be:

import torch

x = torch.tensor([
    [[-0.3000, -0.2926],[-0.2705, -0.2632]],
    [[-0.1821, -0.1747],[-0.1526, -0.1453]],
    [[-0.0642, -0.0568],[-0.0347, -0.0274]]
])

print(x.view(x.size(0), -1).max(dim=-1))

# output:
# >>> values=tensor([-0.2632, -0.1453, -0.0274]),
# >>> indices=tensor([3, 3, 3]))

因此,如果您只需要值:x.view(x.size(0), -1).max(dim=-1).values.

So, if you need only the values: x.view(x.size(0), -1).max(dim=-1).values.

如果 x 不是连续张量,则 .view() 将失败.在这种情况下,您应该使用 .reshape() 代替.

If x is not a contiguous tensor, then .view() will fail. In this case, you should use .reshape() instead.

2020 年 8 月 26 日更新

此功能正在PR#43092中实现,函数将被调用<代码>amin 和 amax.他们将只返回值.这可能很快就会被合并,所以当你阅读这篇文章时,你可能能够在每晚构建时访问这些功能:) 玩得开心.

This feature is being implemented in PR#43092 and the functions will be called amin and amax. They will return only the values. This is probably being merged soon, so you might be able to access these functions on the nightly build by the time you're reading this :) Have fun.

这篇关于多个维度上的 PyTorch torch.max的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆