找回密码
 立即注册
首页 业界区 安全 MindSpore中的ReduceMax和max操作的区别

MindSpore中的ReduceMax和max操作的区别

姬宜欣 2025-6-16 13:15:29
问题背景

在原生的Python中,我们使用求最大值max操作,只会得到计算之后的最大值结果。但是在一些深度学习框架中,特别是在多维的场景下,除了得到一系列的最大值之外,还会得到最大值对应的索引。而MindSpore则支持了两种不同的模式(分别依托于两个算子),既可以输出最大值+索引,也可以只输出最大值。
案例演示

首先用PyTorch来演示一下普通的max算子的计算结果:
  1. In [1]: import torch as tc
  2. In [2]: a = tc.arange(9).reshape((3,3))
  3. In [3]: print (a)
  4. tensor([[0, 1, 2],
  5.         [3, 4, 5],
  6.         [6, 7, 8]])
  7. In [4]: tc.max(a, -1)
  8. Out[4]:
  9. torch.return_types.max(
  10. values=tensor([2, 5, 8]),
  11. indices=tensor([2, 2, 2]))
复制代码
得到的是一个像字典一样的数据结构,values就是最大值,indices是最大值所在维度的编号。在pytorch里面,没有找到reduce_max的实现,也就是只有这种输出形式。不过在mindspore中,除了普通的max算子,还支持了一个ReduceMax算子:
  1. In [1]: import mindspore as ms
  2. In [2]: from mindspore import Tensor, ops
  3. In [3]: a = ms.numpy.arange(9).reshape((3,3))
  4. In [4]: print (a)
  5. [[0 1 2]
  6. [3 4 5]
  7. [6 7 8]]
  8. In [7]: b = ops.ReduceMax(keep_dims=False)(a, -1)
  9. In [8]: print (b)
  10. [2 5 8]
  11. In [9]: c = ops.max(a, -1)
  12. In [10]: c
  13. Out[10]:
  14. (Tensor(shape=[3], dtype=Int32, value= [2, 5, 8]),
  15. 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

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册