引用自: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可能的一个作用。