行列式、逆矩阵与转置
使用 np.linalg.det 计算矩阵行列式,使用 np.linalg.inv 计算逆矩阵,并使用 .T 进行转置
行列式、逆矩阵与转置 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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)) # ~0Computing 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.
常见问题解答
「行列式、逆矩阵与转置」课时是免费的吗?
是的 — 「行列式、逆矩阵与转置」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「行列式、逆矩阵与转置」这节课中我会学到什么?
使用 np.linalg.det 计算矩阵行列式,使用 np.linalg.inv 计算逆矩阵,并使用 .T 进行转置 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「行列式、逆矩阵与转置」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。