argmax python
Dans ce tutoriel, nous allons en apprendre davantage sur la fonction numpy.argmax() en Python. Cette fonction renvoie les indices des éléments maximaux d’une matrice.
np argmax
Recherche de l’élément maximal à partir d’une matrice avec Python numpy.argmax()
import numpy as np a = np.arange(12).reshape(4,3) + 11 print(a)
Production
[[11 12 13] [14 15 16] [17 18 19] [20 21 22]]
arg max python
Trouvons l’index de l’élément maximum dans le tableau.
print(np.argmax(a))
Production
11
- Nous obtenons 11 comme sortie. En effet, lorsqu’aucun axe n’est mentionné à la fonction
numpy.argmax()
, l’index se trouve dans le tableau aplati.- Sans l’axe spécifié, la fonction Python
numpy.argmax()
renvoie le nombre d’éléments dans le tableau.- Nous pouvons utiliser la fonction
np.unravel_index
pour obtenir un index correspondant à un tableau 2D à partir de la sortienumpy.argmax
.
argmax numpy
Utilisation de np.unravel_index
sur la sortie argmax
index = np.unravel_index(np.argmax(a), a.shape) print(index) print(a[index])
Production
(3, 2) 22
Voici le code complet
import numpy as np a = np.arange(12).reshape(4,3) + 11 index = np.unravel_index(np.argmax(a), a.shape) print(a) print(index) print(a[index])
Recherche d’éléments maximaux le long des lignes et des colonnes
import numpy as np a = np.arange(12).reshape(4,3) + 11 print(a) print(np.argmax(a, axis=0))
Production
[[11 12 13] [14 15 16] [17 18 19] [20 21 22]] [3 3 3]
Cela donne la valeur d’index des éléments maximaux le long de chaque colonne.
axis = 1
alors nous pouvons obtenir les indices des éléments maximaux le long des lignes.
import numpy as np a = np.arange(12).reshape(4,3) + 11 print(a) print(np.argmax(a, axis=1))
Production
[[11 12 13] [14 15 16] [17 18 19] [20 21 22]] [2 2 2 2]