繁体   English   中英

在不使用 max 内置函数的情况下查找最大值和最大值的索引

[英]Find maximum value and indices of a maximum without using max built in functions

正如标题所说,我试图在不使用内置 max 函数的任何变体的情况下找到参数的最大值和位置。

我能够将它拼凑成一个基本的np.array ,但我很难将它转换成矩阵......我认为是因为它是如何索引的。

这是我对np.array

a = np.array((1,2,2,3,4,3,2,1,4,3))

def argmax(x):
    maximum = 0
    for i in range(len(x)):
        if x[i] > maximum: maximum = x[i]
    pos = np.argwhere(x == maximum)[0][0]
    return(print('The maximum value of the array is', maximum, 'and is located at index', pos))

argmax(a)

数组的最大值为 4,位于索引 4。

我正在尝试为任何大小的矩阵创建类似的东西,而不使用内置的 max 函数。 有人可以帮助我使用该函数并帮助我理解基本数组和矩阵之间索引的区别吗?

这适用于一维数组和二维数组:

import numpy as np
import math

matrix = np.arange(20).reshape(4, 5)
print(matrix)
# Important
matrix = np.atleast_2d(matrix)
# set maximum to -inf
maximum = -math.inf
# Search maximum
for j in range(matrix.shape[1]):
    for i in range(matrix.shape[0]):
        maximum = matrix[i][j] if matrix[i][j] > maximum else maximum

# More than 1 maximum, take the first one?
pos = np.argwhere(matrix == maximum)[0]
print(
    f"The maximum value of the array is: {maximum}, located at: row {pos[0]}, column {pos[1]}"
)

输出:

[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]
The maximum value of the array is: 19, located at: row 3, column 4

这是对任何形状和尺寸数组执行此操作的方法(它假定值是非负的,因为您用 0 初始化最大值并仅像您在原始答案中所做的那样返回最大值的第一个发生率。当然,您可以轻松更改它们):

def argmax(x):
    maximum = 0
    for i, v in enumerate(x.reshape(-1)):
        if v > maximum: 
            maximum = v
            pos = i
    print('The maximum value of the array is', maximum, 'and is located at index', np.unravel_index(pos, x.shape))

argmax(a)

例子:

a = np.random.randint(0,10,(3,4))
#[[7 6 2 6]
# [7 2 0 5]
# [4 0 8 7]]

输出:

The maximum value of the array is 8 and is located at index (2, 2)

我假设您想沿给定轴找到最大值。 否则,请执行np.unravel_index(argmax(a.ravel()), a.shape)

首先让我们定义一个函数,它沿着给定的维度步进并跟踪它们出现的最大值和索引:

def argmax(a, axis):
    # index
    cur = [slice(None) for _ in range(a.ndim)]
    cur[axis] = 0

    # trackers
    val = a[tuple(index)]
    ind = np.zeros(val.shape, dtype=int)

    # loop
    for i in range(1, a.shape[axis]):
        index[axis] = i
        v = a[tuple(index)]
        mask = v > val
        val[mask] = v[mask]
        ind[mask] = i
    return ind

这将返回沿axis的索引。 如果您想获得其他索引,请执行以下操作

all_indices = list(np.indices(a.shape))
all_indices[axis] = ind
all_indices = tuple(all indices)

或者,

all_indices = [slice(None) for _ range(a.ndim)]
all_indices[axis] = ind
all_indices = tuple(all indices)

这个函数跳过了几个a.shape[axis] == 0情况,比如a.shape[axis] == 0a.ndim == 0 ,但你可以通过简单的初步测试轻松处理它们。

您还可以使用递归调用来处理特殊情况axis=None ,如答案开头所示。

如果您想同时允许多个轴,请将它们全部交换到最后,并将它们重塑为单个轴。 所以axis=None和正常处理的混合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM