NumPy / PyTorch 中的argmax函数

本文介绍了如何在Python的NumPy和PyTorch库中使用argmax函数分别找出二维数组和张量中每列、每行的最大值索引,以及整个矩阵或张量的最大值及其索引。
摘要由CSDN通过智能技术生成

argmax 函数用于找到数组中最大元素的索引。

行或列的最大值: 

import numpy as np  

arr_2d = np.array([[1, 2, 3],  
                   [4, 5, 6],  
                   [7, 8, 9]])  
  
# 使用 argmax 找到每列的最大值的索引(沿着行的方向,axis=0)  
max_indices_per_column = np.argmax(arr_2d, axis=0)  
print("每列的最大值的索引:", max_indices_per_column)  
# 输出: [2 2 2],因为每列的最大值都在第三行。  
  
# 使用 argmax 找到每行的最大值的索引(沿着列的方向,axis=1)  
max_indices_per_row = np.argmax(arr_2d, axis=1)  
print("每行的最大值的索引:", max_indices_per_row)  
# 输出: [2 2 2],因为每行的最大值都在第三列。

import torch  
  
# 创建一个二维 PyTorch 张量  
tensor_2d = torch.tensor([[1, 2, 3],  
                          [4, 5, 6],  
                          [7, 8, 9]])  
  
# 使用 argmax 找到每列的最大值的索引(沿着行的方向,dim=0)  
max_indices_per_column = torch.argmax(tensor_2d, dim=0)  
print("每列的最大值的索引:", max_indices_per_column)  
# 输出: tensor([2, 2, 2]),因为每列的最大值都在第三行。  
  
# 使用 argmax 找到每行的最大值的索引(沿着列的方向,dim=1)  
max_indices_per_row = torch.argmax(tensor_2d, dim=1)  
print("每行的最大值的索引:", max_indices_per_row)  
# 输出: tensor([2, 2, 2]),因为每行的最大值都在第三列。

整个矩阵的最大值:

import numpy as np  
  
# 创建一个二维 NumPy 数组  
arr_2d = np.array([[1, 2, 3],  
                   [4, 5, 9],  
                   [7, 8, 6]])  
  
# 使用 argmax 找到整个矩阵中最大值的索引  
max_index = np.argmax(arr_2d)  
  
# 由于这是一个二维数组,我们需要将一维索引转换为二维坐标  
row = max_index // arr_2d.shape[1]  
col = max_index % arr_2d.shape[1]  
  
print("最大值的索引(行,列):", (row, col))  
# 最大值的索引(行,列): (1, 2)

import torch  
  
# 创建一个二维 PyTorch 张量  
tensor_2d = torch.tensor([[1, 2, 3],  
                          [4, 5, 9], 
                          [7, 8, 6]])  
  
# 将二维张量展平为一维张量  
tensor_flat = tensor_2d.view(-1)  
  
# 使用 argmax 找到整个张量中最大值的索引  
max_index = torch.argmax(tensor_flat)  
  
# 如果需要,可以将一维索引转换为原始的二维坐标  
row = max_index // tensor_2d.size(1)  
col = max_index % tensor_2d.size(1)  
  
print("最大值的索引(行,列):", (row, col))  
# 最大值的索引(行,列): (tensor(1), tensor(2))
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值