0Pricing
Pandas & NumPy Academy · Leçon

Déterminants, inverses et transposées

Calculez les déterminants de matrices avec np.linalg.det, les inverses avec np.linalg.inv et les transposées avec .T.

Déterminants, inverses et transposées est une leçon Pandas & NumPy Academy gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Pandas & NumPy Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Pandas & NumPy Academy comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

The Transpose of a Matrix

The transpose of a matrix flips it over its diagonal: rows become columns and columns become rows. If A has shape (m, n), then A.T has shape (n, m). Transposes appear everywhere in linear algebra: computing covariance matrices, implementing gradient backpropagation, and converting between row-vector and column-vector conventions. NumPy accesses the transpose with the .T attribute — no copy is made, it is just a view with reordered strides.

import numpy as np

A = np.array([[1, 2, 3],
              [4, 5, 6]])
print('A shape:', A.shape)       # (2, 3)
print('A.T shape:', A.T.shape)   # (3, 2)
print(A.T)

Transpose in Practice

A frequent pattern is computing A.T @ A, which produces a symmetric square matrix that appears in least squares regression, PCA, and normal equations. If A has shape (n, p), then A.T @ A has shape (p, p). The result is always symmetric because (A.T @ A)[i,j] == (A.T @ A)[j,i]. This property is exploited by many numerical solvers for efficiency.

import numpy as np

A = np.array([[1.0, 2.0],
              [3.0, 4.0],
              [5.0, 6.0]])  # shape (3, 2)

ATA = A.T @ A   # shape (2, 2), symmetric
print('A.T @ A:')
print(ATA)
print('Is symmetric:', np.allclose(ATA, ATA.T))

The Determinant: What It Means

The determinant of a square matrix is a scalar value that encodes geometric information: it measures the factor by which the matrix scales areas (2-D) or volumes (higher dimensions). A determinant of zero means the matrix is singular — it collapses space onto a lower-dimensional subspace and has no inverse. A non-zero determinant guarantees the matrix is invertible. NumPy computes it with np.linalg.det().

import numpy as np

# Non-singular matrix
A = np.array([[3.0, 1.0],
              [2.0, 4.0]])
print('det(A):', np.linalg.det(A))   # 3*4 - 1*2 = 10

# Singular matrix (row 2 = 2 * row 1)
B = np.array([[1.0, 2.0],
              [2.0, 4.0]])
print('det(B):', np.linalg.det(B))   # ~0

Computing the Inverse with np.linalg.inv()

The inverse of a matrix A, written A⁻¹, satisfies A @ A⁻¹ = I where I is the identity matrix. Inverses exist only for square, non-singular matrices. np.linalg.inv(A) computes the inverse numerically. In practice, you should rarely compute inverses explicitly because it is numerically unstable; prefer np.linalg.solve() for systems of equations instead. But understanding inverses conceptually is essential.

import numpy as np

A = np.array([[3.0, 1.0],
              [2.0, 4.0]])

A_inv = np.linalg.inv(A)
print('Inverse:')
print(A_inv)

# Verify: A @ A_inv should be identity
I = A @ A_inv
print('A @ A_inv (should be I):')
print(np.round(I, 10))

Numerical Instability of Direct Inversion

Computing the inverse of a matrix and then multiplying introduces floating-point errors that compound. For example, solving A_inv @ b is less accurate than calling np.linalg.solve(A, b) directly. A well-conditioned matrix (determinant far from zero) is less sensitive to these errors. The condition number (np.linalg.cond(A)) quantifies how close a matrix is to singular — high condition numbers signal numerical trouble.

import numpy as np

A = np.array([[1.0, 2.0],
              [1.0001, 2.0]])
print('Condition number:', np.linalg.cond(A))
# Very high condition number -> near-singular, unstable inversion

b = np.array([3.0, 3.0001])
# Prefer solve over inv @ b
print('Solution via solve:', np.linalg.solve(A, b))

Orthogonal Matrices and Their Transposes

A special class of matrices is orthogonal matrices, where A.T @ A = I. This means the transpose IS the inverse, making orthogonal matrices extremely cheap to invert. Rotation matrices and the Q factor in QR decomposition are orthogonal. The columns of an orthogonal matrix form an orthonormal basis — each column has unit length and is perpendicular to every other column.

import numpy as np

# 90-degree rotation matrix is orthogonal
theta = np.pi / 2
R = np.array([[np.cos(theta), -np.sin(theta)],
              [np.sin(theta),  np.cos(theta)]])

print('R.T @ R (should be identity):')
print(np.round(R.T @ R, 10))
print('Is orthogonal:', np.allclose(R.T @ R, np.eye(2)))

The Pseudo-Inverse for Non-Square Matrices

A regular inverse only exists for square matrices, but the Moore-Penrose pseudo-inverse generalises inversion to any matrix. np.linalg.pinv(A) computes it using SVD. It is the basis of the least-squares solution to over-determined systems (more equations than unknowns), which is exactly what linear regression solves. If A is square and invertible, pinv(A) equals inv(A).

import numpy as np

# Over-determined system: 3 equations, 2 unknowns
A = np.array([[1.0, 1.0],
              [1.0, 2.0],
              [1.0, 3.0]])
b = np.array([2.0, 3.0, 5.0])

# Least-squares solution using pseudo-inverse
x = np.linalg.pinv(A) @ b
print('Best-fit solution:', x)
# Or use lstsq directly
x2, _, _, _ = np.linalg.lstsq(A, b, rcond=None)
print('lstsq solution:', x2)

Determinant Sign and Volume Scaling

The sign of the determinant indicates whether the transformation preserves or reverses orientation. A positive determinant means orientation is preserved (like a rotation); a negative determinant means orientation is flipped (like a reflection). The absolute value gives the volume scaling factor. For a 2×2 matrix [[a,b],[c,d]], det = a*d - b*c. NumPy handles arbitrary square sizes efficiently.

import numpy as np

# Identity: det = 1 (no scaling, no flip)
I = np.eye(3)
print('det(I):', np.linalg.det(I))    # 1.0

# Scaling by 2 in all directions: det = 8 = 2^3
S = 2 * np.eye(3)
print('det(2I):', np.linalg.det(S))   # 8.0

# Reflection: det = -1
F = np.array([[-1.0, 0.0],
              [ 0.0, 1.0]])
print('det(reflection):', np.linalg.det(F))

Using np.linalg.slogdet() for Stability

For large matrices, the determinant can overflow or underflow to zero even when the matrix is non-singular. np.linalg.slogdet(A) returns (sign, log_abs_det) — the sign and the natural log of the absolute determinant — which avoids numerical overflow. This is widely used in probabilistic models (Gaussian likelihoods) where you work in log-space to keep numbers manageable.

import numpy as np

A = np.random.rand(100, 100)

# Direct det might underflow for large matrices
sign, logdet = np.linalg.slogdet(A)
print('Sign:', sign)
print('Log|det|:', logdet)
print('Actual det (may be ~0 due to float):', np.linalg.det(A))
print('Reconstructed |det|:', np.exp(logdet))

Practical: Solving 2x2 by Hand vs NumPy

For a 2×2 matrix [[a, b], [c, d]], the inverse is (1/det) * [[d, -b], [-c, a]] where det = ad - bc. Knowing this formula helps you spot-check NumPy's result. For anything larger, computing the inverse analytically is impractical — that is precisely why we use np.linalg.inv(). Always verify numerical results with np.allclose(A @ A_inv, np.eye(n)).

import numpy as np

a, b, c, d = 3.0, 1.0, 2.0, 4.0
A = np.array([[a, b], [c, d]])
det = a*d - b*c

# Manual inverse
A_inv_manual = (1/det) * np.array([[d, -b], [-c, a]])
print('Manual inv:')
print(A_inv_manual)

# NumPy inverse
print('np.linalg.inv:')
print(np.linalg.inv(A))
print('Match:', np.allclose(A_inv_manual, np.linalg.inv(A)))

Combining Transpose and Inverse in Pipelines

A common linear algebra pattern combines transpose and inverse: computing (A.T @ A)⁻¹ @ A.T gives the projection matrix used in ordinary least squares. In NumPy, this can be written as np.linalg.inv(A.T @ A) @ A.T but again, np.linalg.lstsq is numerically preferable. Knowing the underlying pattern helps you understand what the solver is doing and debug issues when matrices are near-singular.

import numpy as np

# Design matrix for simple linear regression (with bias)
X = np.column_stack([np.ones(5), np.array([1., 2., 3., 4., 5.])])
y = np.array([2.1, 3.9, 6.2, 8.1, 9.8])

# OLS via normal equations: beta = (X.T @ X)^-1 @ X.T @ y
beta = np.linalg.inv(X.T @ X) @ X.T @ y
print('Coefficients (intercept, slope):', np.round(beta, 3))

# Verify with lstsq
beta2, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
print('lstsq result:', np.round(beta2, 3))

Quick Check

Test your understanding of Data Analysis concepts from this lesson.

Lesson Recap

In this lesson you learned: A.T is the transpose that swaps rows and columns, np.linalg.inv() computes the matrix inverse but should rarely be used directly (prefer solve or lstsq), and np.linalg.det() returns the determinant which is zero for singular matrices. Next up we explore solving linear systems directly with np.linalg.solve.

Questions Fréquemment Posées

La leçon « Déterminants, inverses et transposées » est-elle gratuite ?

Oui — le texte complet de « Déterminants, inverses et transposées » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Pandas & NumPy Academy, passe à CoddyKit PRO. Le cours Pandas & NumPy Academy comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Déterminants, inverses et transposées » ?

Calculez les déterminants de matrices avec np.linalg.det, les inverses avec np.linalg.inv et les transposées avec .T. Tu pratiques Pandas & NumPy Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Pandas & NumPy Academy ?

Aucune expérience préalable n'est requise. Pandas & NumPy Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.

Combien de temps prend la leçon « Déterminants, inverses et transposées » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Pandas & NumPy Academy ?

Oui. Chaque leçon Pandas & NumPy Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Multiplication matricielle avec np.matmul et @
  2. Déterminants, inverses et transposées
  3. Résolution de systèmes linéaires
  4. Valeurs propres et présentation de la SVD
← Retour à Pandas & NumPy Academy