numpy.argmax#
- numpy.argmax(a, axis=None, out=None, *, keepdims=<no value>)[原始碼]#
傳回沿著軸的最大值的索引。
- 參數:
- aarray_like
輸入陣列。
- axisint,選用
預設情況下,索引會指向展平的陣列,否則會沿著指定的軸。
- outarray,選用
如果提供,結果將插入此陣列。它應具有適當的形狀和 dtype。
- keepdimsbool,選用
如果設定為 True,則縮減的軸會保留在結果中,作為大小為 1 的維度。使用此選項,結果將正確地與陣列進行廣播。
在 1.22.0 版本中新增。
- 傳回:
- index_array整數的 ndarray
陣列索引的陣列。它的形狀與
a.shape
相同,並沿著 axis 移除維度。如果 keepdims 設定為 True,則 axis 的大小將為 1,且產生的陣列具有與a.shape
相同的形狀。
另請參閱
ndarray.argmax
、argmin
amax
沿著給定軸的最大值。
unravel_index
將扁平索引轉換為索引元組。
take_along_axis
從 argmax 將
np.expand_dims(index_array, axis)
應用於陣列,如同呼叫 max 一樣。
註解
在最大值多次出現的情況下,會傳回對應於第一次出現的索引。
範例
>>> import numpy as np >>> a = np.arange(6).reshape(2,3) + 10 >>> a array([[10, 11, 12], [13, 14, 15]]) >>> np.argmax(a) 5 >>> np.argmax(a, axis=0) array([1, 1, 1]) >>> np.argmax(a, axis=1) array([2, 2])
N 維陣列的最大元素索引
>>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape) >>> ind (1, 2) >>> a[ind] 15
>>> b = np.arange(6) >>> b[1] = 5 >>> b array([0, 5, 2, 3, 4, 5]) >>> np.argmax(b) # Only the first occurrence is returned. 1
>>> x = np.array([[4,2,3], [1,0,3]]) >>> index_array = np.argmax(x, axis=-1) >>> # Same as np.amax(x, axis=-1, keepdims=True) >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1) array([[4], [3]]) >>> # Same as np.amax(x, axis=-1) >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), ... axis=-1).squeeze(axis=-1) array([4, 3])
將 keepdims 設定為 True,
>>> x = np.arange(24).reshape((2, 3, 4)) >>> res = np.argmax(x, axis=1, keepdims=True) >>> res.shape (2, 1, 4)