torch.max, torch.gather

引用自:https://blog.csdn.net/Z_lbj/article/details/79766690

torch.max

torch.max(input) → Tensor

返回输入tensor中所有元素的最大值

a = torch.randn(1, 3)
>>0.4729 -0.2266 -0.2085
 
torch.max(a)
>>0.4729
 
torch.max(input, dim, keepdim=False, out=None) -> (Tensor, LongTensor)

按维度dim 返回最大值

torch.max)(a,0) 返回每一列中最大值的那个元素,且返回索引(返回最大元素在这一列的行索引

a = torch.randn(3,3)
>>
0.2252 -0.0901  0.5663
-0.4694  0.8073  1.3596
 0.1073 -0.7757 -0.8649
 
torch.max(a,0)
>>
(
 0.2252
 0.8073
 1.3596
[torch.FloatTensor of size 3]
, 
 0
 1
 1
[torch.LongTensor of size 3]
)

torch.max(a,1) 返回每一行中最大值的那个元素,且返回其索引(返回最大元素在这一行的列索引)

a = torch.randn(3,3)
>>
0.2252 -0.0901  0.5663
-0.4694  0.8073  1.3596
 0.1073 -0.7757 -0.8649
 
torch.max(a,1)

(
 0.5663
 1.3596
 0.1073
[torch.FloatTensor of size 3]
, 
 2
 2
 0
[torch.LongTensor of size 3]
)

torch.max()[0], 只返回最大值的每个数

troch.max()[1], 只返回最大值的每个索引

torch.max()[1].data 只返回variable中的数据部分(去掉Variable containing:)

torch.max()[1].data.numpy() 把数据转化成numpy ndarry

torch.max()[1].data.numpy().squeeze() 把数据条目中维度为1 的删除掉

torch.max(tensor1,tensor2) element-wise 比较tensor1 和tensor2 中的元素,返回较大的那个值

torch.gather()

首先我们来看官方文档:

torch.gather(input, dim, index, out=None) → Tensor

    Gathers values along an axis specified by dim.

    For a 3-D tensor the output is specified by:

    out[i][j][k] = input[index[i][j][k]][j][k]  # dim=0
    out[i][j][k] = input[i][index[i][j][k]][k]  # dim=1
    out[i][j][k] = input[i][j][index[i][j][k]]  # dim=2

    Parameters:	

        input (Tensor) – The source tensor
        dim (int) – The axis along which to index
        index (LongTensor) – The indices of elements to gather
        out (Tensor, optional) – Destination tensor

    Example:

    >>> t = torch.Tensor([[1,2],[3,4]])
    >>> torch.gather(t, 1, torch.LongTensor([[0,0],[1,0]]))
     1  1
     4  3
    [torch.FloatTensor of size 2x2]

先来看torch.gather, 核心操作其实就是这样:

out[i][j][k] = input[index[i][j][k]] [j][k] # if dim == 0

out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1

out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2

是对于out指定位置上的值,去寻找input里面对应的索引位置,根据是index索引。
我们再来看官方文档给的例子:

    >>> t = torch.Tensor([[1,2],[3,4]])
    >>> torch.gather(t, 1, torch.LongTensor([[0,0],[1,0]]))
     1  1
     4  3
    [torch.FloatTensor of size 2x2]

out[0][0] = input[0][ index[0][0] ] = input[0][0] = 1

out[0][1] = input[0][ index[0][1] ] = input[0][0] = 1

out[1][0] = input[1][ index[1][0] ] = input[1][1] = 4

out[1][1] = input[1][ index[1][1] ] = input[1][0] = 3

gather在one-hot为输出的多分类问题中,可以把最大值坐标作为index传进去,然后提取到每一行的正确预测结果,这也是gather可能的一个作用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值