[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,66 +2,159 @@
|
||||
id: wiki-2026-0508-linear-algebra
|
||||
title: Linear Algebra
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-LIAL-001]
|
||||
aliases: [Linear Algebra for ML, Vectors and Matrices, SVD, Eigendecomposition]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.99
|
||||
tags: [auto-reinforced, linear-algebra, mathematics, vectors, matrices, Deep-Learning, machine-learning]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [math, linear-algebra, numpy, svd, eigen, pca, ml-foundations]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack: { language: Python, framework: numpy/torch }
|
||||
---
|
||||
|
||||
# [[Linear-Algebra|Linear-Algebra]]
|
||||
# Linear Algebra
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터의 다차원 언어: 방대한 수치 데이터를 벡터와 행렬이라는 격자에 담아 한꺼번에 움직이고 회전시키며 연산하게 함으로써, 수조 개의 파라미터를 가진 신경망이 눈 깜짝할 새 답을 내놓게 하는 현대 인공지능의 물리적 토대."
|
||||
## 매 한 줄
|
||||
> **"매 ML은 행렬 곱셈이다"**. Vector·Matrix·Tensor 위에서 projection, rotation, decomposition으로 모든 게 표현된다.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
선형 대수학(Linear-Algebra)은 벡터 공간, 선형 사상 등을 다루는 수학의 한 분야입니다.
|
||||
## 매 핵심
|
||||
### 매 객체
|
||||
- Scalar, Vector ∈ ℝⁿ, Matrix ∈ ℝᵐˣⁿ, Tensor (high-rank).
|
||||
- Norms: ‖x‖₁ (sparsity), ‖x‖₂ (energy), ‖x‖∞.
|
||||
- Inner product, outer product, cosine similarity.
|
||||
|
||||
1. **AI를 지탱하는 핵심 병기**:
|
||||
* **Vectors**: 정보의 방향과 크기를 담은 점. (Embedding과 연결)
|
||||
* **Matrices**: 벡터들을 묶은 표. 데이터를 변환하는 '연산자' 역할.
|
||||
* **Dot Product (내적)**: 두 벡터가 얼마나 닮았는지(유사도) 계산. (Attention 메커니즘의 기초)
|
||||
* **Eigenvalues/Vectors**: 행렬의 핵심 성격(주성분)을 파악. (PCA와 연결)
|
||||
2. **왜 중요한가?**:
|
||||
* 딥러닝의 모든 학습과 추론은 결국 거대한 '행렬 곱셈'의 반복이기 때문임. (GPU 하드웨어가 이 연산에 목숨 거는 이유)
|
||||
### 매 연산 핵심
|
||||
- Matmul C=AB. shape (m,k)·(k,n)=(m,n).
|
||||
- Transpose, inverse, pseudoinverse (Moore-Penrose).
|
||||
- Determinant (scaling), trace (diagonal sum, eigen sum).
|
||||
- Rank: 독립 column 수. low-rank → 압축 가능.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 수동 계산 정책 위주의 순수 수학이었으나, 현대 정책은 수십억 개의 행렬 연산을 병렬 처리 정책으로 소화하는 '수치 해석학 및 계산 수학 정책'으로 패러다임이 바뀜(RL Update). ([[High-Performance Computing (HPC)|High-Performance Computing (HPC)]]와 연결)
|
||||
- **정책 변화(RL Update)**: 최근에는 단순한 실수 연산을 넘어, 양자 연산이나 희소 행렬(Sparse Matrix) 최적화 정책 등 하드웨어 효율 정책을 극대화하는 선형 대수 기법들이 주목받음.
|
||||
### 매 분해
|
||||
- **Eigendecomposition** A = QΛQ⁻¹ (square, diagonalizable). PCA covariance.
|
||||
- **SVD** A = UΣVᵀ (any matrix). 가장 일반적.
|
||||
- **QR** Gram-Schmidt. least squares 안정.
|
||||
- **Cholesky** A = LLᵀ (symm. PD). 빠른 solve, GP, Kalman.
|
||||
- **LU** general solve.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Hardware|Hardware]], [[High-Performance Computing (HPC)|High-Performance Computing (HPC)]], Deep Learning (DL), [[Backpropagation|Backpropagation]], [[Gradient-Descent|Gradient-Descent]]
|
||||
- **Modern Tech/Tools**: NumPy, PyTorch (Tensor library), MATLAB, CuBLAS (NVIDIA).
|
||||
---
|
||||
### 매 ML 응용
|
||||
1. **PCA**: covariance eigen / data SVD → top-k.
|
||||
2. **Linear regression**: x̂ = (XᵀX)⁻¹Xᵀy 또는 SVD pseudoinverse.
|
||||
3. **Recommendation MF**: A ≈ UVᵀ.
|
||||
4. **Word embeddings**: LSA SVD, word2vec implicit MF.
|
||||
5. **Attention**: softmax(QKᵀ/√d)V — 전부 matmul.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
### NumPy 핵심
|
||||
```python
|
||||
import numpy as np
|
||||
A = np.random.randn(4, 3); x = np.random.randn(3)
|
||||
y = A @ x # matmul
|
||||
G = A.T @ A # 3x3 Gram
|
||||
inv = np.linalg.inv(G)
|
||||
sol = np.linalg.solve(G, A.T @ y) # 안정적인 normal eq
|
||||
```
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### SVD & truncated rank-k
|
||||
```python
|
||||
U, S, Vt = np.linalg.svd(A, full_matrices=False)
|
||||
k = 2
|
||||
A_k = U[:, :k] @ np.diag(S[:k]) @ Vt[:k]
|
||||
```
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Eigen / PCA
|
||||
```python
|
||||
X = np.random.randn(1000, 10)
|
||||
Xc = X - X.mean(0)
|
||||
cov = Xc.T @ Xc / (len(X) - 1)
|
||||
vals, vecs = np.linalg.eigh(cov) # symmetric → eigh
|
||||
order = np.argsort(-vals)
|
||||
PCs = vecs[:, order[:3]]
|
||||
Z = Xc @ PCs # (N, 3)
|
||||
```
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### Least squares 4가지
|
||||
```python
|
||||
# 1) normal eq (불안정)
|
||||
b1 = np.linalg.inv(A.T @ A) @ A.T @ y
|
||||
# 2) solve (better)
|
||||
b2 = np.linalg.solve(A.T @ A, A.T @ y)
|
||||
# 3) lstsq (SVD-based, 가장 안정)
|
||||
b3, *_ = np.linalg.lstsq(A, y, rcond=None)
|
||||
# 4) pseudoinverse
|
||||
b4 = np.linalg.pinv(A) @ y
|
||||
```
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### einsum (general tensor)
|
||||
```python
|
||||
# batch matmul (B,M,K)·(B,K,N) → (B,M,N)
|
||||
C = np.einsum("bmk,bkn->bmn", X, Y)
|
||||
# attention scores
|
||||
scores = np.einsum("bqd,bkd->bqk", Q, K) / np.sqrt(Q.shape[-1])
|
||||
```
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### Norms / cosine
|
||||
```python
|
||||
def cosine(a, b):
|
||||
return (a @ b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-12)
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### PyTorch (autograd)
|
||||
```python
|
||||
import torch
|
||||
A = torch.randn(4, 3, requires_grad=True)
|
||||
loss = (A @ x - y).pow(2).sum()
|
||||
loss.backward() # dL/dA
|
||||
U, S, Vt = torch.linalg.svd(A, full_matrices=False)
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### Cholesky (GP / Kalman)
|
||||
```python
|
||||
L = np.linalg.cholesky(K + 1e-6 * np.eye(n)) # K SPD + jitter
|
||||
alpha = np.linalg.solve(L.T, np.linalg.solve(L, y))
|
||||
```
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
## 매 결정 기준
|
||||
| 작업 | 함수 |
|
||||
|---|---|
|
||||
| 일반 solve | `np.linalg.solve` |
|
||||
| Least squares | `np.linalg.lstsq` (SVD) |
|
||||
| Symm. eigen | `eigh` |
|
||||
| 일반 eigen | `eig` |
|
||||
| 일반 분해 | `svd` |
|
||||
| SPD solve 빠르게 | Cholesky |
|
||||
| Sparse 큰 행렬 | `scipy.sparse.linalg` (eigsh, svds) |
|
||||
| GPU | torch.linalg / cupy |
|
||||
|
||||
**기본값**: 정확도/안정성은 SVD/Cholesky, 속도는 solve, 빠른 prototype은 lstsq.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Mathematics]], [[Numerical-Methods]]
|
||||
- 변형: [[SVD]], [[Eigendecomposition]], [[QR-Decomposition]], [[Cholesky]]
|
||||
- 응용: [[PCA]], [[Linear-Regression]], [[Latent-Semantic-Analysis-LSA]], [[Attention]]
|
||||
- Adjacent: [[Tensor]], [[Numpy]], [[Optimization]], [[Calculus]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 식 유도, einsum 변환, 함수 선택, shape debug.
|
||||
**언제 X**: numerical conditioning / iterative solver tuning은 전문가.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- `inv(A) @ b` 대신 `solve(A, b)` 안 씀
|
||||
- Symm 행렬에 일반 `eig` (느림+정확도)
|
||||
- Large dense에 raw SVD (메모리) → randomized/truncated
|
||||
- Loop matmul (vectorize)
|
||||
- 차원/축 mismatch — `einsum`으로 명시
|
||||
- Float32 누적 오차 (PCA covariance) → float64 또는 standardize
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Strang, Trefethen NLA, NumPy/PyTorch docs). 신뢰도 A.
|
||||
- 중복: 없음.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — einsum, lstsq, Cholesky 패턴 추가 |
|
||||
|
||||
Reference in New Issue
Block a user