{
  "id": "linear-algebra",
  "module": "math-ml",
  "level": 2,
  "minutes": 35,
  "audiences": [
    "beginner",
    "researcher"
  ],
  "software": [],
  "text": {
    "en": {
      "title": "Linear Algebra for AI: Vectors, Matrix Multiplication, Eigendecomposition and SVD",
      "description": "Linear algebra for machine learning: vectors, dot products and cosine similarity; matrix multiplication as a linear map; rank and linear independence; eigenvalues and eigenvectors; the singular value decomposition (SVD) and Eckart–Young low-rank approximation; and how these ideas appear in word vectors, attention QKᵀ/√d, PCA and LoRA. Based on original papers and official documentation, with runnable NumPy code.",
      "updated": "2026-11-10",
      "takeaways": [
        "A vector is an ordered list of numbers that can represent a word, an image or a layer's activations. The dot product equals the product of lengths times the cosine of the angle; cosine similarity divides out the lengths and compares direction only, which is why it is the standard measure for comparing embeddings.",
        "Matrix multiplication composes linear maps: applying R and then S is the same as multiplying by SR. A fully connected layer is y = Wx + b, and Transformer attention scores are QKᵀ.",
        "Rank is the number of linearly independent directions among a matrix's columns. A d×k matrix of rank r factors into a d×r and an r×k matrix, which is why LoRA can write a weight update as BA and cut trainable parameters from dk to r(d+k).",
        "SVD factors any matrix as UΣVᵀ. Eckart and Young (1936) proved that, in the Frobenius norm, truncating to the top k singular values gives the best rank-k approximation, with error equal to the square root of the sum of the squared discarded singular values.",
        "PCA is equivalent to the SVD of the centred data matrix: the right singular vectors are the principal directions and the squared singular values are proportional to the variance along each direction."
      ],
      "faq": [
        {
          "q": "How much linear algebra do I need for deep learning?",
          "a": "For reading papers and writing code you should be fluent with vector and matrix shapes, matrix multiplication and transposes, dot products and norms, rank, eigenvalues and eigenvectors, and SVD. Determinants and Jordan normal form are rarely used directly in LLM work. MIT 18.06 and chapters 2–4 of Mathematics for Machine Learning cover everything listed above."
        },
        {
          "q": "What is the difference between cosine similarity and the dot product?",
          "a": "The dot product a·b = ‖a‖‖b‖cosθ depends on both length and direction; cosine similarity cosθ = a·b /(‖a‖‖b‖) depends on direction only and lies between −1 and 1. When vectors are L2-normalised the two are equal, which is why many vector databases search normalised embeddings with the inner product."
        },
        {
          "q": "Why does attention divide by √d_k?",
          "a": "Vaswani et al. (2017) explain that if the components of q and k are independent with mean 0 and variance 1, then q·k has variance d_k. Large dimensions produce large dot products that push the softmax into regions with extremely small gradients; dividing by √d_k brings the variance back to about 1. In this lesson's demo, the unscaled variance at d_k = 256 is about 258 and the scaled variance about 1.0."
        },
        {
          "q": "How are SVD and eigendecomposition related?",
          "a": "Eigendecomposition needs a square, diagonalisable matrix; real symmetric matrices can always be orthogonally diagonalised. SVD exists for any m×n matrix: the right singular vectors of A are eigenvectors of AᵀA and the singular values are the square roots of its eigenvalues. Numerical work on non-square or ill-conditioned matrices usually relies on SVD."
        },
        {
          "q": "Is LoRA the same thing as low-rank SVD approximation?",
          "a": "No. Low-rank SVD compresses a known matrix. LoRA freezes the pretrained weight W₀, parameterises the unknown update ΔW directly as a low-rank product BA, and trains B and A by gradient descent. What they share is the fact that a rank-r matrix is described by only r(d+k) numbers. The LoRA paper also uses SVD to analyse the subspaces of the learned ΔW."
        }
      ],
      "sources": [
        {
          "title": "MIT OpenCourseWare: 18.06 Linear Algebra (Gilbert Strang)",
          "url": "https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/"
        },
        {
          "title": "MIT OpenCourseWare: 18.065 Matrix Methods in Data Analysis, Signal Processing, and Machine Learning",
          "url": "https://ocw.mit.edu/courses/18-065-matrix-methods-in-data-analysis-signal-processing-and-machine-learning-spring-2018/"
        },
        {
          "title": "Deisenroth, Faisal, Ong: Mathematics for Machine Learning (official free edition)",
          "url": "https://mml-book.github.io/"
        },
        {
          "title": "Dive into Deep Learning: 2.3 Linear Algebra",
          "url": "https://d2l.ai/chapter_preliminaries/linear-algebra.html"
        },
        {
          "title": "NumPy documentation: Linear algebra (numpy.linalg)",
          "url": "https://numpy.org/doc/stable/reference/routines.linalg.html"
        },
        {
          "title": "PyTorch documentation: torch.linalg",
          "url": "https://docs.pytorch.org/docs/stable/linalg.html"
        },
        {
          "title": "Eckart & Young (1936), The Approximation of One Matrix by Another of Lower Rank, Psychometrika",
          "url": "https://doi.org/10.1007/BF02288367"
        },
        {
          "title": "Pearson (1901), On lines and planes of closest fit to systems of points in space",
          "url": "https://doi.org/10.1080/14786440109462720"
        },
        {
          "title": "scikit-learn documentation: Decomposing signals in components (PCA and more)",
          "url": "https://scikit-learn.org/stable/modules/decomposition.html"
        },
        {
          "title": "Mikolov et al. (2013), Efficient Estimation of Word Representations in Vector Space",
          "url": "https://arxiv.org/abs/1301.3781"
        },
        {
          "title": "Vaswani et al. (2017), Attention Is All You Need",
          "url": "https://arxiv.org/abs/1706.03762"
        },
        {
          "title": "Hu et al. (2021), LoRA: Low-Rank Adaptation of Large Language Models",
          "url": "https://arxiv.org/abs/2106.09685"
        },
        {
          "title": "Aghajanyan, Zettlemoyer, Gupta (2020), Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning",
          "url": "https://arxiv.org/abs/2012.13255"
        },
        {
          "title": "Li et al. (2018), Measuring the Intrinsic Dimension of Objective Landscapes",
          "url": "https://arxiv.org/abs/1804.08838"
        },
        {
          "title": "3Blue1Brown: Essence of Linear Algebra",
          "url": "https://www.3blue1brown.com/?topic=linear-algebra"
        },
        {
          "title": "Khan Academy: Linear algebra",
          "url": "https://www.khanacademy.org/math/linear-algebra"
        }
      ],
      "url": "https://aimap.page/en/learn/math-ml/linear-algebra/",
      "markdown": "**Overview**: Linear algebra is the language in which embeddings, neural-network layers and attention are written. This lesson proceeds from vectors to matrix multiplication, rank, eigendecomposition, and finally SVD and low-rank approximation, tying each topic to a concrete use in large models: cosine similarity for vector search, matrix multiplication for dense layers and attention, and low-rank structure for PCA and LoRA.\n\nThis lesson belongs to the [Linear Algebra](/learn/unit/u11-linalg) unit; the prerequisite is [Python and NumPy setup](/learn/python-numpy-setup). Continue with [Calculus and Optimization](/learn/calculus-optimization), [Tokens and Embeddings](/learn/tokens-embeddings), [Transformers and Attention](/learn/transformer-attention) and [Fine-tuning and LoRA](/learn/fine-tuning-lora). Related algorithm cards: [PCA](/learn/algorithms/pca), [Word2Vec](/learn/algorithms/word2vec), [Transformer](/learn/algorithms/transformer), [LoRA](/learn/algorithms/lora).\n\n## Vectors, dot products and cosine similarity\n\nAn n-dimensional vector x ∈ ℝⁿ is an ordered list of n real numbers. In machine learning it may be a word embedding, the flattened pixels of an image, or the activations of a layer.\n\nThe **dot product** (inner product) of two vectors is a·b = Σᵢ aᵢbᵢ = aᵀb, which geometrically equals ‖a‖‖b‖cos θ, where ‖a‖ = √(aᵀa) is the L2 norm and θ the angle between them. **Cosine similarity** divides out the lengths:\n\n```text\ncos θ = aᵀb / (‖a‖‖b‖)  ∈ [−1, 1]\n```\n\n| Cosine | Geometry | Usual reading for embeddings |\n|---|---|---|\n| 1 | Same direction | Very similar meaning |\n| 0 | Orthogonal | No linear relation in direction |\n| −1 | Opposite direction | Opposite under this representation |\n\nMikolov et al. (2013) introduced the CBOW and Skip-gram architectures of Word2Vec and examined semantic and syntactic relations with vector arithmetic; for example, vector(\"King\") − vector(\"Man\") + vector(\"Woman\") is closest to vector(\"Queen\") ([Mikolov et al., 2013](https://arxiv.org/abs/1301.3781)). Such \"directions as relations\" are measured with dot products and cosine similarity. Modern vector databases search L2-normalised embeddings with the inner product, which is equivalent to ranking by cosine similarity; see [Vector Databases](/learn/vector-databases).\n\n## Matrix multiplication as a linear map\n\nAn m×n matrix A maps vectors in ℝⁿ to ℝᵐ: y = Ax. The map is linear: A(αx + βz) = αAx + βAz. The product SR is the composite map \"first R, then S\", so in general SR ≠ RS.\n\nShape rules are what you check most often when writing model code: (m×n)(n×p) = (m×p); the inner dimensions must match.\n\n| Where | Operation | Shape (single example) |\n|---|---|---|\n| Dense layer | y = Wx + b | W: dₒᵤₜ×dᵢₙ |\n| Embedding lookup | one-hot vector times embedding matrix | E: V×d, pick row i |\n| Attention scores | QKᵀ | (n×dₖ)(dₖ×n) = n×n |\n| Attention output | softmax(·)V | (n×n)(n×dᵥ) |\n\nThe Transformer's scaled dot-product attention is Attention(Q, K, V) = softmax(QKᵀ/√dₖ)V. Vaswani et al. explain the √dₖ: if the components of q and k are independent with mean 0 and variance 1, then q·k has variance dₖ, and for large dimensions the softmax is pushed into regions with extremely small gradients ([Vaswani et al., 2017](https://arxiv.org/abs/1706.03762)). The demo below checks this numerically.\n\n## Rank, linear independence and low-rank structure\n\nA set of vectors is **linearly independent** if none of them can be written as a linear combination of the others. The **rank** of a matrix is the maximum number of linearly independent columns (equivalently, rows), i.e. the number of independent directions it spans.\n\nA direct consequence: a d×k matrix of rank r can always be written as the product of a d×r and an r×k matrix, reducing storage from dk to r(d+k). When r ≪ min(d, k) the saving is large.\n\nThis structure appears repeatedly in large models:\n\n- **LoRA**: Hu et al. (2021) freeze the pretrained weight W₀ and write the update as ΔW = BA with B ∈ ℝ^(d×r), A ∈ ℝ^(r×k), r ≪ min(d, k). The abstract reports that, compared with fine-tuning GPT-3 175B with Adam, LoRA reduces trainable parameters by about 10,000 times and GPU memory by about 3 times ([Hu et al., 2021](https://arxiv.org/abs/2106.09685)).\n- **Intrinsic dimension**: Li et al. (2018) train networks in random subspaces and find that many problems need an \"intrinsic dimension\" far smaller than the parameter count ([Li et al., 2018](https://arxiv.org/abs/1804.08838)). Aghajanyan et al. (2020) report that optimising only 200 parameters, randomly projected back into the full space, lets RoBERTa reach 90% of full fine-tuning performance on MRPC ([Aghajanyan et al., 2020](https://arxiv.org/abs/2012.13255)). The LoRA paper cites such results to motivate its hypothesis that weight updates have a low intrinsic rank.\n\nFor a single 4096×4096 projection matrix (measured output of this lesson's demo):\n\n| LoRA rank r | Full parameters dk | LoRA parameters r(d+k) | Reduction |\n|---|---|---|---|\n| 4 | 16,777,216 | 32,768 | 512× |\n| 8 | 16,777,216 | 65,536 | 256× |\n| 16 | 16,777,216 | 131,072 | 128× |\n| 64 | 16,777,216 | 524,288 | 32× |\n\n## Eigenvalues and eigenvectors\n\nFor a square matrix A, a non-zero vector v with Av = λv is an eigenvector and λ the corresponding eigenvalue: A only stretches v, without changing its direction.\n\nReal symmetric matrices (covariance matrices, Hessians of quadratic functions) have an important property: they can be orthogonally diagonalised, A = QΛQᵀ, where the columns of Q are orthonormal eigenvectors and Λ is the diagonal matrix of real eigenvalues. This is used directly in two places:\n\n1. **PCA**: the eigenvectors of the covariance matrix give the principal directions; the eigenvalues are the variances along them.\n2. **Optimisation**: on a quadratic f(w) = ½wᵀAw, the convergence speed of gradient descent is governed by the ratio of the largest to the smallest eigenvalue (the condition number); see [Calculus and Optimization](/learn/calculus-optimization).\n\n## Singular value decomposition and optimal low-rank approximation\n\nEvery real m×n matrix can be factored as\n\n```text\nA = U Σ Vᵀ\n```\n\nwhere U (m×m) and V (n×n) are orthogonal and the diagonal of Σ holds the non-negative singular values σ₁ ≥ σ₂ ≥ … ≥ 0. The number of non-zero singular values equals the rank. The link to eigendecomposition: the columns of V are eigenvectors of AᵀA, and σᵢ² are its eigenvalues.\n\nKeeping the top k singular values gives the truncated SVD Aₖ = Σᵢ₌₁ᵏ σᵢuᵢvᵢᵀ. Eckart and Young (1936) proved that, in the Frobenius norm, Aₖ is the closest matrix to A among all matrices of rank at most k, with error\n\n```text\n‖A − A_k‖_F = √( Σ_{i>k} σᵢ² )\n```\n\n([Eckart & Young, 1936](https://doi.org/10.1007/BF02288367)). This gives a single view of compression and denoising: large singular values carry the main structure, small ones are often noise.\n\n**PCA and SVD**: Pearson (1901) framed PCA as finding the lines and planes of closest fit to a set of points ([Pearson, 1901](https://doi.org/10.1080/14786440109462720)). For a centred data matrix X (one example per row), the right singular vectors are the principal directions and the variance along direction i is σᵢ²/(n−1). scikit-learn's `PCA` likewise centres each feature (without scaling) and then applies SVD ([scikit-learn documentation](https://scikit-learn.org/stable/modules/decomposition.html)).\n\n## Runnable example\n\nThe NumPy script below demonstrates, in turn: composition of maps, cosine similarity, eigendecomposition, low-rank SVD and the Eckart–Young error, LoRA parameter counts, and the variance of attention scores. It was run under Python 3.13 and NumPy 2.5 with a fixed seed and is reproducible.\n\n```python\nimport numpy as np\nrng = np.random.default_rng(0)\n\n# 1) A matrix is a linear map: rotate by 90°, then stretch x by 2\nR = np.array([[0., -1.], [1., 0.]])\nS = np.array([[2., 0.], [0., 1.]])\nx = np.array([1., 0.])\nprint(\"S@(R@x) =\", S @ (R @ x), \" (S@R)@x =\", (S @ R) @ x)\n\n# 2) Dot product and cosine similarity\ndef cos(a, b):\n    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))\na, b, c = np.array([1., 2., 0.]), np.array([2., 4., 0.]), np.array([-2., 1., 0.])\nprint(\"cos(a,b) =\", round(cos(a, b), 4), \" cos(a,c) =\", round(cos(a, c), 4))\n\n# 3) Eigendecomposition (symmetric matrix)\nA = np.array([[2., 1.], [1., 2.]])\nw, V = np.linalg.eigh(A)\nprint(\"eigenvalues =\", w)\n\n# 4) Low-rank SVD: a rank-2 signal plus noise\nn = 64\nu = np.linspace(-1, 1, n)\nimg = (np.outer(np.cos(3 * u), np.sin(2 * u)) + 0.5 * np.outer(u, u ** 2)\n       + 0.05 * rng.standard_normal((n, n)))\nU, s, Vt = np.linalg.svd(img, full_matrices=False)\nfor k in (1, 2, 4, 8, 16):\n    Ak = (U[:, :k] * s[:k]) @ Vt[:k]\n    err = np.linalg.norm(img - Ak)            # Frobenius norm\n    tail = np.sqrt((s[k:] ** 2).sum())         # error predicted by Eckart–Young\n    print(f\"k={k:2d} rel_err={err / np.linalg.norm(img):.4f} \"\n          f\"frob_err={err:.4f} tail_sigma={tail:.4f}\")\n\n# 5) LoRA parameter count: ΔW = B A, B: d×r, A: r×k\nd = k = 4096\nfor r in (4, 8, 16, 64):\n    print(f\"r={r:3d} full={d * k:,} lora={r * (d + k):,}\")\n\n# 6) Attention-score variance grows with d_k; dividing by sqrt(d_k) restores ~1\nfor dk in (16, 64, 256):\n    q = rng.standard_normal((20000, dk)); kk = rng.standard_normal((20000, dk))\n    dots = (q * kk).sum(1)\n    print(f\"d_k={dk:3d} var={dots.var():7.2f} scaled_var={(dots / np.sqrt(dk)).var():.3f}\")\n```\n\nKey points from the measured output:\n\n- Both orders of evaluation give `[0. 1.]`; `cos(a,b)=1.0` (same direction) and `cos(a,c)=0.0` (orthogonal); the symmetric matrix `[[2,1],[1,2]]` has eigenvalues 1 and 3.\n- The noisy image has full rank (64), but its signal has rank 2: the relative error is 0.2589 at k = 1, drops sharply to 0.0868 at k = 2, and then falls slowly (0.0558 at k = 16); what remains is mostly noise. On every row `frob_err` equals `tail_sigma` (e.g. 3.0893 at k = 2), as the Eckart–Young theorem predicts.\n- Attention scores: for dₖ = 16, 64, 256 the unscaled variances are about 15.97, 63.28 and 257.85; after dividing by √dₖ they are 0.998, 0.989 and 1.007.\n\n## Where these concepts appear in large models\n\n| Concept | Where it appears | Further reading |\n|---|---|---|\n| Dot product, cosine similarity | Embedding search, attention scores | [Tokens and Embeddings](/learn/tokens-embeddings) |\n| Matrix multiplication | Dense layers, Q/K/V projections, output layer | [Transformers and Attention](/learn/transformer-attention) |\n| Rank and low-rank factorisation | LoRA, QLoRA and other parameter-efficient fine-tuning | [Fine-tuning and LoRA](/learn/fine-tuning-lora) |\n| Eigendecomposition | Covariance, Hessians and conditioning | [Calculus and Optimization](/learn/calculus-optimization) |\n| SVD | PCA, low-rank compression, analysing learned weights | [PCA card](/learn/algorithms/pca) |\n\n## Exercises\n\n1. **Unit project**: load a greyscale image (or use the synthetic one above), compute truncated SVDs for k = 1, 2, 4, …, plot rank k against relative reconstruction error, and use this lesson's LoRA parameter formula to explain why a few directions can describe a weight update.\n2. Complete the vectors, matrix multiplication and eigenvalue practice sets in [Khan Academy Linear Algebra](https://www.khanacademy.org/math/linear-algebra).\n3. Work through problem sets and past exams from [MIT 18.06](https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/); for matrix methods in machine learning, continue with [MIT 18.065](https://ocw.mit.edu/courses/18-065-matrix-methods-in-data-analysis-signal-processing-and-machine-learning-spring-2018/).\n4. Use `numpy.linalg` or `torch.linalg` to compute `svd`, `eigh` and `matrix_rank` for the same matrix, and check that the eigenvalues of AᵀA equal the squared singular values ([NumPy docs](https://numpy.org/doc/stable/reference/routines.linalg.html), [PyTorch docs](https://docs.pytorch.org/docs/stable/linalg.html)).\n\n## Suggested order of study\n\nStart with [3Blue1Brown's Essence of Linear Algebra](https://www.3blue1brown.com/?topic=linear-algebra) for geometric intuition, then use [D2L section 2.3](https://d2l.ai/chapter_preliminaries/linear-algebra.html) to put the concepts into tensor code; for systematic study, take MIT 18.06 or chapters 2–4 of [Mathematics for Machine Learning](https://mml-book.github.io/) (linear algebra, analytic geometry, matrix decompositions). Then continue with [Calculus and Optimization](/learn/calculus-optimization)."
    },
    "zh-hans": {
      "title": "AI 中的线性代数：向量、矩阵乘法、特征分解与 SVD",
      "description": "面向机器学习的线性代数：向量与点积、余弦相似度，矩阵乘法作为线性变换，秩与线性无关，特征值与特征向量，奇异值分解（SVD）与 Eckart–Young 低秩近似，以及这些概念在词向量、注意力 QKᵀ/√d、PCA 与 LoRA 中的具体用法。依据原始论文与官方文档，附可运行的 NumPy 示例。",
      "updated": "2026-11-10",
      "takeaways": [
        "向量是一组有序的数，可以表示一个词、一张图片或一层激活；两个向量的点积等于长度乘积再乘夹角余弦，余弦相似度把长度除掉，只比较方向，是向量检索和嵌入比较的常用度量。",
        "矩阵乘法是线性变换的复合：先做 R 再做 S 等价于直接乘 SR。神经网络的全连接层就是 y = Wx + b，Transformer 的注意力打分是 QKᵀ。",
        "秩是矩阵列向量中线性无关方向的个数。秩为 r 的 d×k 矩阵可以写成 d×r 与 r×k 两个矩阵的乘积，这正是 LoRA 用 BA 表示权重增量、把可训练参数从 dk 降到 r(d+k) 的依据。",
        "SVD 把任意矩阵分解为 UΣVᵀ。Eckart 与 Young（1936）证明：在 Frobenius 范数下，保留前 k 个奇异值得到的截断 SVD 是最优的秩 k 近似，误差等于被丢弃奇异值平方和的平方根。",
        "PCA 等价于对中心化数据矩阵做 SVD：右奇异向量给出主成分方向，奇异值平方与各方向的方差成正比。"
      ],
      "faq": [
        {
          "q": "学深度学习需要掌握多少线性代数？",
          "a": "日常读论文和写代码，需要熟练掌握：向量与矩阵的形状、矩阵乘法与转置、点积与范数、秩、特征值与特征向量、SVD。行列式、若尔当标准形等内容在大模型相关工作中较少直接用到。MIT 18.06 与《Mathematics for Machine Learning》第 2–4 章覆盖了上述全部内容。"
        },
        {
          "q": "余弦相似度和点积有什么区别？",
          "a": "点积 a·b = ‖a‖‖b‖cosθ 同时受长度和方向影响；余弦相似度 cosθ = a·b /(‖a‖‖b‖) 只看方向，取值在 −1 到 1。向量事先做了 L2 归一化时，两者相等，因此许多向量数据库在归一化嵌入上直接用内积检索。"
        },
        {
          "q": "为什么注意力要除以 √d_k？",
          "a": "Vaswani 等（2017）的解释是：若 q、k 的各分量独立、均值 0、方差 1，则 q·k 的方差为 d_k。维度越大，点积数值越大，softmax 会进入梯度极小的饱和区。除以 √d_k 把方差拉回约 1。本课示例实测 d_k=256 时未缩放的方差约 258，缩放后约 1.0。"
        },
        {
          "q": "SVD 和特征分解是什么关系？",
          "a": "特征分解要求方阵，且只有可对角化矩阵才有；实对称矩阵总能正交对角化。SVD 对任意 m×n 矩阵都存在：A 的右奇异向量是 AᵀA 的特征向量，奇异值是 AᵀA 特征值的平方根。数值计算中处理非方阵或病态矩阵时通常用 SVD。"
        },
        {
          "q": "LoRA 和 SVD 低秩近似是一回事吗？",
          "a": "不是。SVD 低秩近似是对已知矩阵做压缩；LoRA 冻结预训练权重 W₀，把待学习的增量 ΔW 直接参数化为低秩乘积 BA，再用梯度下降训练 B 和 A。两者共享的是“秩 r 的矩阵只需 r(d+k) 个数描述”这一事实。LoRA 论文还用 SVD 分析了学到的 ΔW 的子空间。"
        }
      ],
      "sources": [
        {
          "title": "MIT OpenCourseWare：18.06 Linear Algebra（Gilbert Strang）",
          "url": "https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/"
        },
        {
          "title": "MIT OpenCourseWare：18.065 Matrix Methods in Data Analysis, Signal Processing, and Machine Learning",
          "url": "https://ocw.mit.edu/courses/18-065-matrix-methods-in-data-analysis-signal-processing-and-machine-learning-spring-2018/"
        },
        {
          "title": "Deisenroth、Faisal、Ong：Mathematics for Machine Learning（官方免费版）",
          "url": "https://mml-book.github.io/"
        },
        {
          "title": "Dive into Deep Learning：2.3 Linear Algebra",
          "url": "https://d2l.ai/chapter_preliminaries/linear-algebra.html"
        },
        {
          "title": "NumPy 文档：Linear algebra (numpy.linalg)",
          "url": "https://numpy.org/doc/stable/reference/routines.linalg.html"
        },
        {
          "title": "PyTorch 文档：torch.linalg",
          "url": "https://docs.pytorch.org/docs/stable/linalg.html"
        },
        {
          "title": "Eckart、Young（1936），The Approximation of One Matrix by Another of Lower Rank，Psychometrika",
          "url": "https://doi.org/10.1007/BF02288367"
        },
        {
          "title": "Pearson（1901），On lines and planes of closest fit to systems of points in space",
          "url": "https://doi.org/10.1080/14786440109462720"
        },
        {
          "title": "scikit-learn 文档：Decomposing signals in components（PCA 等）",
          "url": "https://scikit-learn.org/stable/modules/decomposition.html"
        },
        {
          "title": "Mikolov 等（2013），Efficient Estimation of Word Representations in Vector Space",
          "url": "https://arxiv.org/abs/1301.3781"
        },
        {
          "title": "Vaswani 等（2017），Attention Is All You Need",
          "url": "https://arxiv.org/abs/1706.03762"
        },
        {
          "title": "Hu 等（2021），LoRA: Low-Rank Adaptation of Large Language Models",
          "url": "https://arxiv.org/abs/2106.09685"
        },
        {
          "title": "Aghajanyan、Zettlemoyer、Gupta（2020），Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning",
          "url": "https://arxiv.org/abs/2012.13255"
        },
        {
          "title": "Li 等（2018），Measuring the Intrinsic Dimension of Objective Landscapes",
          "url": "https://arxiv.org/abs/1804.08838"
        },
        {
          "title": "3Blue1Brown：Essence of Linear Algebra（线性代数的本质）",
          "url": "https://www.3blue1brown.com/?topic=linear-algebra"
        },
        {
          "title": "Khan Academy：Linear algebra",
          "url": "https://www.khanacademy.org/math/linear-algebra"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/math-ml/linear-algebra/",
      "markdown": "**概要**：线性代数是描述嵌入、神经网络层与注意力的基本语言。本课按“向量 → 矩阵乘法 → 秩 → 特征分解 → SVD 与低秩近似”的顺序展开，每一节都对应到大模型中的一个具体用法：余弦相似度用于向量检索，矩阵乘法构成全连接层与注意力，低秩结构支撑 PCA 与 LoRA。\n\n本课属于[线性代数：向量、矩阵与分解](/learn/unit/u11-linalg)单元，前置为 [Python 与 NumPy 环境](/learn/python-numpy-setup)。后续可接[微积分与优化](/learn/calculus-optimization)、[分词与嵌入](/learn/tokens-embeddings)、[Transformer 与注意力](/learn/transformer-attention)和[微调与 LoRA](/learn/fine-tuning-lora)。相关算法卡：[PCA](/learn/algorithms/pca)、[Word2Vec](/learn/algorithms/word2vec)、[Transformer](/learn/algorithms/transformer)、[LoRA](/learn/algorithms/lora)。\n\n## 向量、点积与余弦相似度\n\n一个 n 维向量 x ∈ ℝⁿ 是 n 个有序实数。在机器学习中，它可以是一个词的嵌入、一张图片展平后的像素，或者某层网络的激活。\n\n两个向量的**点积**（内积）定义为 a·b = Σᵢ aᵢbᵢ = aᵀb，几何上等于 ‖a‖‖b‖cos θ。其中 ‖a‖ = √(aᵀa) 是 L2 范数，θ 是夹角。**余弦相似度**把长度除掉：\n\n```text\ncos θ = aᵀb / (‖a‖‖b‖)  ∈ [−1, 1]\n```\n\n| 余弦值 | 几何含义 | 在嵌入中的常见解读 |\n|---|---|---|\n| 1 | 方向相同 | 语义高度相近 |\n| 0 | 正交 | 方向上无线性相关 |\n| −1 | 方向相反 | 在该表示下相反 |\n\nMikolov 等（2013）提出 Word2Vec 的 CBOW 与 Skip-gram 两种结构，并用向量运算考察词的语义与句法关系，例如 vector(\"King\") − vector(\"Man\") + vector(\"Woman\") 最接近 vector(\"Queen\")（[Mikolov 等，2013](https://arxiv.org/abs/1301.3781)）。这类“方向即关系”的现象，就是用点积和余弦相似度来度量的。今天的向量数据库在 L2 归一化后的嵌入上做内积检索，等价于按余弦相似度排序，见[向量数据库](/learn/vector-databases)。\n\n## 矩阵乘法即线性变换\n\nm×n 矩阵 A 把 ℝⁿ 中的向量映射到 ℝᵐ：y = Ax。它满足线性：A(αx + βz) = αAx + βAz。矩阵乘法 SR 对应“先做 R，再做 S”的复合变换，因此一般 SR ≠ RS。\n\n形状规则是写模型代码时最常检查的内容：(m×n)(n×p) = (m×p)，内侧维度必须相等。\n\n| 场景 | 矩阵运算 | 形状（单个样本） |\n|---|---|---|\n| 全连接层 | y = Wx + b | W：dₒᵤₜ×dᵢₙ |\n| 词嵌入查表 | one-hot 向量乘嵌入矩阵 | E：V×d，取第 i 行 |\n| 注意力打分 | QKᵀ | (n×dₖ)(dₖ×n) = n×n |\n| 注意力输出 | softmax(·)V | (n×n)(n×dᵥ) |\n\nTransformer 的缩放点积注意力定义为 Attention(Q, K, V) = softmax(QKᵀ/√dₖ)V。Vaswani 等解释了除以 √dₖ 的原因：若 q、k 各分量独立、均值 0、方差 1，则 q·k 的方差为 dₖ，维度大时 softmax 会被推入梯度极小的区域（[Vaswani 等，2017](https://arxiv.org/abs/1706.03762)）。下文示例对此做了数值验证。\n\n## 秩、线性无关与低秩结构\n\n一组向量**线性无关**，指其中任何一个都不能由其余向量线性组合得到。矩阵的**秩**是其列（等价地，行）中线性无关向量的最大个数，也就是它能“张成”的独立方向数。\n\n秩的一个直接推论：秩为 r 的 d×k 矩阵总能写成 d×r 与 r×k 两个矩阵之积，存储量从 dk 降到 r(d+k)。当 r ≪ min(d, k) 时，节省非常可观。\n\n这一结构在大模型中反复出现：\n\n- **LoRA**：Hu 等（2021）冻结预训练权重 W₀，把增量写成 ΔW = BA，B ∈ ℝ^(d×r)、A ∈ ℝ^(r×k)，r ≪ min(d, k)；论文摘要报告，与用 Adam 全量微调 GPT-3 175B 相比，可训练参数减少约 10000 倍，GPU 显存需求降为约三分之一（[Hu 等，2021](https://arxiv.org/abs/2106.09685)）。\n- **内在维度**：Li 等（2018）在随机子空间中训练网络，发现许多问题所需的“内在维度”远小于参数总数（[Li 等，2018](https://arxiv.org/abs/1804.08838)）；Aghajanyan 等（2020）报告，只优化随机投影回全参数空间的 200 个参数，就能让 RoBERTa 在 MRPC 上达到全参数微调 90% 的效果（[Aghajanyan 等，2020](https://arxiv.org/abs/2012.13255)）。LoRA 论文以这类结果作为“权重更新具有低内在秩”这一假设的动机。\n\n以 d = k = 4096 的一个投影矩阵为例（本课示例的实测输出）：\n\n| LoRA 秩 r | 全量参数 dk | LoRA 参数 r(d+k) | 压缩倍数 |\n|---|---|---|---|\n| 4 | 16,777,216 | 32,768 | 512 |\n| 8 | 16,777,216 | 65,536 | 256 |\n| 16 | 16,777,216 | 131,072 | 128 |\n| 64 | 16,777,216 | 524,288 | 32 |\n\n## 特征值与特征向量\n\n对方阵 A，若非零向量 v 满足 Av = λv，则 v 是特征向量，λ 是对应的特征值：A 作用在 v 上只做伸缩，不改变方向。\n\n实对称矩阵（如协方差矩阵、二次函数的 Hessian）有一条重要性质：可以正交对角化，A = QΛQᵀ，Q 的列是两两正交的单位特征向量，Λ 为实特征值组成的对角阵。这条性质在两处直接用到：\n\n1. **PCA**：协方差矩阵的特征向量给出主成分方向，特征值是该方向上的方差。\n2. **优化**：二次函数 f(w) = ½wᵀAw 上梯度下降的收敛速度由最大与最小特征值之比（条件数）决定，见[微积分与优化](/learn/calculus-optimization)。\n\n## 奇异值分解（SVD）与最优低秩近似\n\n任意 m×n 实矩阵都可以分解为\n\n```text\nA = U Σ Vᵀ\n```\n\n其中 U（m×m）与 V（n×n）为正交矩阵，Σ 的对角线上是非负的奇异值 σ₁ ≥ σ₂ ≥ … ≥ 0。非零奇异值的个数等于矩阵的秩。与特征分解的关系是：V 的列是 AᵀA 的特征向量，σᵢ² 是对应的特征值。\n\n保留前 k 个奇异值得到截断 SVD Aₖ = Σᵢ₌₁ᵏ σᵢuᵢvᵢᵀ。Eckart 与 Young（1936）证明，在 Frobenius 范数下，Aₖ 是所有秩不超过 k 的矩阵中离 A 最近的一个，误差为\n\n```text\n‖A − A_k‖_F = √( Σ_{i>k} σᵢ² )\n```\n\n（[Eckart 与 Young，1936](https://doi.org/10.1007/BF02288367)）。这给出了压缩与去噪的统一视角：大奇异值对应主要结构，小奇异值往往对应噪声。\n\n**PCA 与 SVD 的关系**：Pearson（1901）把 PCA 表述为寻找最贴近一组点的直线和平面（[Pearson，1901](https://doi.org/10.1080/14786440109462720)）。对中心化后的数据矩阵 X（每行一个样本）做 SVD，右奇异向量就是主成分方向，第 i 个方向上的方差为 σᵢ²/(n−1)。scikit-learn 的 `PCA` 也是先对各特征中心化（不做缩放），再做 SVD（[scikit-learn 文档](https://scikit-learn.org/stable/modules/decomposition.html)）。\n\n## 可运行示例\n\n下面的 NumPy 脚本依次演示：变换复合、余弦相似度、特征分解、SVD 低秩近似与 Eckart–Young 误差、LoRA 参数量，以及注意力打分的方差。本课在 Python 3.13、NumPy 2.5 下实测，随机种子固定，可复现。\n\n```python\nimport numpy as np\nrng = np.random.default_rng(0)\n\n# 1) 矩阵 = 线性变换：先旋转 90°，再沿 x 轴拉伸 2 倍\nR = np.array([[0., -1.], [1., 0.]])\nS = np.array([[2., 0.], [0., 1.]])\nx = np.array([1., 0.])\nprint(\"S@(R@x) =\", S @ (R @ x), \" (S@R)@x =\", (S @ R) @ x)\n\n# 2) 点积与余弦相似度\ndef cos(a, b):\n    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))\na, b, c = np.array([1., 2., 0.]), np.array([2., 4., 0.]), np.array([-2., 1., 0.])\nprint(\"cos(a,b) =\", round(cos(a, b), 4), \" cos(a,c) =\", round(cos(a, c), 4))\n\n# 3) 特征分解（对称矩阵）\nA = np.array([[2., 1.], [1., 2.]])\nw, V = np.linalg.eigh(A)\nprint(\"eigenvalues =\", w)\n\n# 4) SVD 低秩近似：秩 2 的信号 + 噪声\nn = 64\nu = np.linspace(-1, 1, n)\nimg = (np.outer(np.cos(3 * u), np.sin(2 * u)) + 0.5 * np.outer(u, u ** 2)\n       + 0.05 * rng.standard_normal((n, n)))\nU, s, Vt = np.linalg.svd(img, full_matrices=False)\nfor k in (1, 2, 4, 8, 16):\n    Ak = (U[:, :k] * s[:k]) @ Vt[:k]\n    err = np.linalg.norm(img - Ak)            # Frobenius 范数\n    tail = np.sqrt((s[k:] ** 2).sum())         # Eckart–Young 给出的误差\n    print(f\"k={k:2d} rel_err={err / np.linalg.norm(img):.4f} \"\n          f\"frob_err={err:.4f} tail_sigma={tail:.4f}\")\n\n# 5) LoRA 参数量：ΔW = B A，B: d×r，A: r×k\nd = k = 4096\nfor r in (4, 8, 16, 64):\n    print(f\"r={r:3d} full={d * k:,} lora={r * (d + k):,}\")\n\n# 6) 注意力打分方差随 d_k 增长；除以 sqrt(d_k) 后回到约 1\nfor dk in (16, 64, 256):\n    q = rng.standard_normal((20000, dk)); kk = rng.standard_normal((20000, dk))\n    dots = (q * kk).sum(1)\n    print(f\"d_k={dk:3d} var={dots.var():7.2f} scaled_var={(dots / np.sqrt(dk)).var():.3f}\")\n```\n\n实测输出要点：\n\n- 两种写法的变换结果相同，均为 `[0. 1.]`；`cos(a,b)=1.0`（同向），`cos(a,c)=0.0`（正交）；对称矩阵 `[[2,1],[1,2]]` 的特征值为 1 和 3。\n- 含噪图像满秩（rank 64），但信号部分的秩为 2：k = 1 时相对误差 0.2589，k = 2 时骤降到 0.0868，之后下降缓慢（k = 16 时 0.0558），剩余部分主要是噪声。每一行的 `frob_err` 与 `tail_sigma` 完全一致（如 k = 2 时均为 3.0893），与 Eckart–Young 定理相符。\n- 注意力打分：dₖ = 16、64、256 时未缩放方差分别约为 15.97、63.28、257.85，除以 √dₖ 后为 0.998、0.989、1.007。\n\n## 在大模型中的对应关系\n\n| 线性代数概念 | 大模型中的位置 | 延伸阅读 |\n|---|---|---|\n| 点积、余弦相似度 | 嵌入检索、注意力打分 | [分词与嵌入](/learn/tokens-embeddings) |\n| 矩阵乘法 | 全连接层、Q/K/V 投影、输出层 | [Transformer 与注意力](/learn/transformer-attention) |\n| 秩与低秩分解 | LoRA、QLoRA 等参数高效微调 | [微调与 LoRA](/learn/fine-tuning-lora) |\n| 特征分解 | 协方差、Hessian 与优化条件数 | [微积分与优化](/learn/calculus-optimization) |\n| SVD | PCA 降维、低秩压缩、分析学到的权重 | [PCA 算法卡](/learn/algorithms/pca) |\n\n## 动手练习\n\n1. **单元项目**：读入一张灰度图（或用上面的合成图），对 k = 1, 2, 4, … 做截断 SVD，画出“保留秩 k—相对重建误差”曲线，并用本课的 LoRA 参数量公式说明：为什么只保留少数方向就能描述一次权重更新。\n2. 在 [Khan Academy 线性代数](https://www.khanacademy.org/math/linear-algebra)完成向量、矩阵乘法和特征值部分的练习题。\n3. 选做 [MIT 18.06](https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/) 的习题与往年考题；想看矩阵方法在机器学习中的应用，接着学 [MIT 18.065](https://ocw.mit.edu/courses/18-065-matrix-methods-in-data-analysis-signal-processing-and-machine-learning-spring-2018/)。\n4. 用 `numpy.linalg` 或 `torch.linalg` 分别计算同一矩阵的 `svd`、`eigh`、`matrix_rank`，核对 AᵀA 的特征值是否等于奇异值的平方（[NumPy 文档](https://numpy.org/doc/stable/reference/routines.linalg.html)、[PyTorch 文档](https://docs.pytorch.org/docs/stable/linalg.html)）。\n\n## 推荐学习顺序\n\n先看 [3Blue1Brown《线性代数的本质》](https://www.3blue1brown.com/?topic=linear-algebra)建立几何直觉，再按 [D2L 2.3 节](https://d2l.ai/chapter_preliminaries/linear-algebra.html)把概念落到张量代码上，系统学习用 MIT 18.06 或 [Mathematics for Machine Learning](https://mml-book.github.io/) 第 2–4 章（线性代数、解析几何、矩阵分解）。之后进入[微积分与优化](/learn/calculus-optimization)。"
    }
  }
}