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算子,可以允许我们只输出最大值而不输出最大值索引。

版权声明

本文首发链接为:https://www.cnblogs.com/dechinphy/p/reduce_max.html

作者ID:DechinPhy

更多原著文章:https://www.cnblogs.com/dechinphy/

请博主喝咖啡:https://www.cnblogs.com/dechinphy/gallery/image/379634.html

posted @ 2025-06-16 14:52  DECHIN  阅读(33)  评论(0)    收藏  举报