Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Licence CC BY-NC-ND Thierry Parmentelat & Arnaud Legout Inria - UCA

Complément - niveau basique

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.ion()
<contextlib.ExitStack at 0x7f5ee1612030>

Un aspect important de l’utilisation de numpy consiste à manipuler des matrices et vecteurs. Voici une rapide introduction à ces fonctionnalités.

Produit matriciel - np.dot

Rappel : On a déjà vu que * entre deux tableaux faisait une multiplication terme à terme.

ligne = 1 + np.arange(3)
print(ligne)
[1 2 3]
colonne = 1 + np.arange(3).reshape(3, 1)
print(colonne)
[[1]
 [2]
 [3]]

Ce n’est pas ce que l’on veut ici !

# avec le broadcasting, numpy me laisse écrire ceci
# mais **ce n'est pas** un produit matriciel
print(ligne * colonne)
[[1 2 3]
 [2 4 6]
 [3 6 9]]

L’opération de produit matriciel s’appelle np.dot :

m1 = np.array([[1, 1],
               [2, 2]])
print(m1)
[[1 1]
 [2 2]]
m2 = np.array([[10, 20],
               [30, 40]])
print(m2)
[[10 20]
 [30 40]]
# comme fonction
np.dot(m1, m2)
array([[ 40, 60], [ 80, 120]])
# comme méthode
m1.dot(m2)
array([[ 40, 60], [ 80, 120]])

Je vous signale aussi un opérateur spécifique, noté @, qui permet également de faire le produit matriciel.

m1 @ m2
array([[ 40, 60], [ 80, 120]])
m2 @ m1
array([[ 50, 50], [110, 110]])

C’est un opérateur un peu ad hoc pour numpy, puisqu’il ne fait pas de sens avec les types usuels de Python :

for x, y in ( (10, 20), (10., 20.), ([10], [20]), ((10,), (20,))):
    try:
        x @ y
    except Exception as e:
        print(f"OOPS - {type(e)} - {e}")
OOPS - <class 'TypeError'> - unsupported operand type(s) for @: 'int' and 'int'
OOPS - <class 'TypeError'> - unsupported operand type(s) for @: 'float' and 'float'
OOPS - <class 'TypeError'> - unsupported operand type(s) for @: 'list' and 'list'
OOPS - <class 'TypeError'> - unsupported operand type(s) for @: 'tuple' and 'tuple'

Produit scalaire - np.dot ou @

Ici encore, vous pouvez utiliser dot qui va intelligemment transposer le second argument :

v1 = np.array([1, 2, 3])
print(v1)
[1 2 3]
v2 = np.array([4, 5, 6])
print(v2)
[4 5 6]
np.dot(v1, v2)
np.int64(32)
v1 @ v2
np.int64(32)

Transposée

Vous pouvez accéder à une matrice transposée de deux façons :

m = np.arange(4).reshape(2, 2)
print(m)
[[0 1]
 [2 3]]
print(m.T)
[[0 2]
 [1 3]]
print(m)
[[0 1]
 [2 3]]
m.transpose()
array([[0, 2], [1, 3]])

Matrice identité - np.eye

np.eye(4, dtype=np.int8)
array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=int8)

Matrices diagonales - np.diag

Avec np.diag, vous pouvez dans les deux sens :

M = np.arange(4) + 10 * np.arange(4)[:, np.newaxis]
print(M)
[[ 0  1  2  3]
 [10 11 12 13]
 [20 21 22 23]
 [30 31 32 33]]
D = np.diag(M)
print(D)
[ 0 11 22 33]
M2 = np.diag(D)
print(M2)
[[ 0  0  0  0]
 [ 0 11  0  0]
 [ 0  0 22  0]
 [ 0  0  0 33]]

Déterminant - np.linalg.det

Avec la fonction np.linalg.det :

# une isométrie
M = np.array([[0, -1], [1, 0]])
print(M)
[[ 0 -1]
 [ 1  0]]
# et donc
np.linalg.det(M) == 1
np.True_

Valeurs propres - np.linalg.eig

Vous pouvez obtenir valeurs propres et vecteurs propres d’une matrice avec np.eig :

# la symétrie par rapport à x=y
S = np.array([[0, 1], [1, 0]])
values, vectors = np.linalg.eig(S)
# pas de déformation
values
array([ 1., -1.])
# les deux diagonales
vectors
array([[ 0.70710678, -0.70710678], [ 0.70710678, 0.70710678]])

Systèmes d’équations - np.linalg.solve

Fabriquons-nous un système d’équations :

x, y, z = 1, 2, 3
3*x + 2*y + z
10
2*x + 3*y +4*z
20
5*x + 2*y + 6*z
27

On peut le résoudre tout simplement comme ceci :

coefficients= np.array([
    [3, 2, 1],
    [2, 3, 4],
    [5, 2, 6],
])
constants = [
    10,
    20,
    27,
]
X, Y, Z = np.linalg.solve(coefficients, constants)

Par contre bien sûr on est passé par les flottants, et donc on a le souci habituel avec la précision des arrondis :

Z
np.float64(3.0000000000000004)

Résumé

En résumé, ce qu’on vient de voir :

outilpropos
np.dotproduit matriciel
np.dotproduit scalaire
np.transposetransposée
np.eyematrice identité
np.diagextrait la diagonale
np.diagou construit une matrice diagonale
np.linalg.detdéterminant
np.linalg.eigvaleurs propres
np.linalg.solverésout système équations

Pour en savoir plus

Voyez la documentation complète sur l’algèbre linéaire.