MindSpore中的ReduceMax和max操作的區別
問題背景
在原生的Python中,我們使用求最大值max操作,只會得到計算之后的最大值結果。但是在一些深度學習框架中,特別是在多維的場景下,除了得到一系列的最大值之外,還會得到最大值對應的索引。而MindSpore則支持了兩種不同的模式(分別依托于兩個算子),既可以輸出最大值+索引,也可以只輸出最大值。
案例演示
首先用PyTorch來演示一下普通的max算子的計算結果:
In [1]: import torch as tc
In [2]: a = tc.arange(9).reshape((3,3))
In [3]: print (a)
tensor([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
In [4]: tc.max(a, -1)
Out[4]:
torch.return_types.max(
values=tensor([2, 5, 8]),
indices=tensor([2, 2, 2]))
得到的是一個像字典一樣的數據結構,values就是最大值,indices是最大值所在維度的編號。在pytorch里面,沒有找到reduce_max的實現,也就是只有這種輸出形式。不過在mindspore中,除了普通的max算子,還支持了一個ReduceMax算子:
In [1]: import mindspore as ms
In [2]: from mindspore import Tensor, ops
In [3]: a = ms.numpy.arange(9).reshape((3,3))
In [4]: print (a)
[[0 1 2]
[3 4 5]
[6 7 8]]
In [7]: b = ops.ReduceMax(keep_dims=False)(a, -1)
In [8]: print (b)
[2 5 8]
In [9]: c = ops.max(a, -1)
In [10]: c
Out[10]:
(Tensor(shape=[3], dtype=Int32, value= [2, 5, 8]),
Tensor(shape=[3], dtype=Int32, value= [2, 2, 2]))
這個ReduceMax算子,可以只輸出最大值而不輸出索引,這在有些情況下可以節約計算空間。
總結概要
本文介紹了在pytorch和mindspore中兩種計算張量最大值的算子,如果直接使用max算子,兩者的輸出都是最大值元素和最大值索引。但是mindspore中額外的支持了ReduceMax算子,可以允許我們只輸出最大值而不輸出最大值索引。
版權聲明
本文首發鏈接為:http://www.rzrgm.cn/dechinphy/p/reduce_max.html
作者ID:DechinPhy
更多原著文章:http://www.rzrgm.cn/dechinphy/
請博主喝咖啡:http://www.rzrgm.cn/dechinphy/gallery/image/379634.html

本文介紹了在pytorch和mindspore中兩種計算張量最大值的算子,如果直接使用max算子,兩者的輸出都是最大值元素和最大值索引。但是mindspore中額外的支持了ReduceMax算子,可以允許我們只輸出最大值而不輸出最大值索引。
浙公網安備 33010602011771號