[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,90 +2,188 @@
id: wiki-2026-0508-sampling-techniques
title: Sampling Techniques
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-SAMPLING-001]
aliases: [Statistical Sampling, Survey Sampling, MCMC Sampling]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Statistics, sampling, data-science, bootstrap, stratified-sampling, monte-carlo]
confidence_score: 0.9
verification_status: applied
tags: [statistics, sampling, monte-carlo, mcmc, survey]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: python
framework: numpy / numpyro / scikit-learn
---
# Sampling Techniques (샘플링 기법)
# Sampling Techniques
## 📌 한 줄 통찰 (The Karpathy Summary)
> "전체의 거대함에 압도되지 말고 대표성 있는 조각(Sample)을 정교하게 도려내어, 최소한의 자원으로 최대한의 진실을 추론하라" — 모집단 전체를 조사하는 대신 그 일부를 추출하여 전체의 특성을 파악하고 분석 효율을 극대화하는 통계적 방법론.
## 한 줄
> **"매 sampling 은 population 의 representative slice 를 얻는 art"**. Neyman (1934) 의 stratified sampling formalization 부터 매 modern MCMC (NUTS, HMC, SMC) 까지 — 매 statistics, ML 의 LLM-RLHF preference dataset 까지 backbone. 2026 에 Anthropic, OpenAI 의 RLAIF pipeline 도 매 stratified human-preference sampling 의 위에 동작.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Representative Subset Extraction and Bias Mitigation" — 무작위성을 기반으로 하되, 데이터의 층(Strata)이나 구조를 고려하여 표본이 특정 집단에 편중되지 않게 함으로써 추론의 오차(Sampling Error)를 최소화하는 패턴.
- **주요 기법:**
- **Simple Random Sampling:** 모든 요소에게 동일한 추출 기회 부여.
- **Stratified Sampling:** 모집단을 성격이 다른 그룹으로 나누고 각 그룹에서 비례하여 추출 (불균형 데이터 해결).
- **Systematic Sampling:** 일정한 간격으로 추출.
- **Importance Sampling:** 확률 분포가 희소한 지점의 샘플링 효율을 높이는 기법 (강화학습에서 활용).
- **Bootstrap:** 중복 허용 샘플링 (앙상블 학습의 기초).
- **의의:** 빅데이터 시대에도 전수 조사는 비용과 시간 면에서 불가능한 경우가 많으며, 샘플링은 데이터 분석과 머신러닝 학습의 속도와 타당성을 결정짓는 핵심 공정임.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순히 많이 뽑는 것이 좋다는 생각에서 벗어나, 이제는 데이터의 양보다 '얼마나 편향되지 않게 뽑았는가'가 중요해졌으며, 생성 모델(GAN, Diffusion)의 출력 이미지를 고르는 정교한 샘플링 전략으로까지 확장됨.
- **정책 변화:** Antigravity 프로젝트는 1,174개 지식 자산의 품질 검수 시, 시간 효율을 위해 전체의 5%를 층화 추출하여 정밀 검토하는 샘플링 기반의 품질 관리(QA) 프로토콜을 수행함.
### 매 Probability sampling family
- **Simple Random**: 매 uniform pick — baseline 이지만 small subgroup 누락 위험.
- **Stratified**: population 을 stratum 으로 partition, 매 stratum 당 SRS — variance reduction.
- **Cluster**: cluster 단위 pick (e.g. zipcode) — 매 cost↓ but design-effect↑.
- **Systematic**: every k-th — 매 list 가 random 일 때 유효, periodicity 시 bias.
- **Multistage**: cluster → stratified → SRS — 매 national survey 의 표준.
## 🔗 지식 연결 (Graph)
- Pre-Processing-Data-for-AI, [[Prioritized-Experience-Replay|Prioritized-Experience-Replay]], [[Random-Forest-Classifiers|Random-Forest-Classifiers]], [[Probability-Theory-Foundations|Probability-Theory-Foundations]]
- **Raw Source:** 10_Wiki/Topics/AI/Sampling-Techniques.md
### 매 Non-probability (use with care)
- **Convenience**: 매 quickest, biased.
- **Snowball**: 매 hidden population (e.g. underground community).
- **Quota**: 매 demographic match 강제 — Online panel 에서 흔함.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 Monte Carlo / MCMC
- **Importance**: q(x) 에서 sample 후 w=p/q reweight.
- **Rejection**: accept iff u·M·q(x) ≤ p(x).
- **MH/HMC/NUTS**: 매 high-dim posterior — Stan, NumPyro, BlackJAX 의 default.
- **SMC**: 매 sequential Bayes (particle filter generalization).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. RLHF preference data — 매 stratified by task family.
2. A/B test bucketing — 매 hash-mod stratify on user_id.
3. Image diffusion — 매 latent prior sampling (DDIM, EDM2).
4. NN training mini-batch — 매 weighted sampler for class imbalance.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### Stratified split (sklearn)
```python
from sklearn.model_selection import StratifiedShuffleSplit
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
sss = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_idx, test_idx in sss.split(X, y):
X_tr, X_te = X[train_idx], X[test_idx]
y_tr, y_te = y[train_idx], y[test_idx]
```
## 🤔 의사결정 기준 (Decision Criteria)
### Reservoir sampling (streaming, k items)
```python
import random
**선택 A를 써야 할 때:**
- *(TODO)*
def reservoir(stream, k):
res = []
for i, item in enumerate(stream):
if i < k:
res.append(item)
else:
j = random.randint(0, i)
if j < k:
res[j] = item
return res
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Weighted sampling (alias method, O(1) per draw)
```python
import numpy as np
**기본값:**
> *(TODO)*
class AliasSampler:
def __init__(self, weights):
n = len(weights)
p = np.asarray(weights, dtype=np.float64)
p = p * n / p.sum()
self.prob = np.zeros(n); self.alias = np.zeros(n, dtype=np.int64)
small = [i for i in range(n) if p[i] < 1.0]
large = [i for i in range(n) if p[i] >= 1.0]
while small and large:
s, l = small.pop(), large.pop()
self.prob[s] = p[s]; self.alias[s] = l
p[l] -= 1.0 - p[s]
(small if p[l] < 1.0 else large).append(l)
for i in large + small:
self.prob[i] = 1.0
self.n = n
def draw(self, k=1):
i = np.random.randint(0, self.n, size=k)
u = np.random.random(k)
return np.where(u < self.prob[i], i, self.alias[i])
```
## ❌ 안티패턴 (Anti-Patterns)
### NUTS posterior sampling (NumPyro 0.16)
```python
import numpyro, numpyro.distributions as dist
from numpyro.infer import MCMC, NUTS
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
def model(x, y):
a = numpyro.sample("a", dist.Normal(0, 1))
b = numpyro.sample("b", dist.Normal(0, 1))
sigma = numpyro.sample("sigma", dist.HalfNormal(1.0))
numpyro.sample("obs", dist.Normal(a + b * x, sigma), obs=y)
mcmc = MCMC(NUTS(model), num_warmup=1000, num_samples=2000)
mcmc.run(jax.random.PRNGKey(0), x, y)
```
### Importance sampling (with effective sample size)
```python
def importance(samples, log_p, log_q):
log_w = log_p - log_q
log_w -= log_w.max()
w = np.exp(log_w); w /= w.sum()
ess = 1.0 / np.sum(w ** 2)
return w, ess
```
### Hash-mod A/B bucketing (deterministic)
```python
import hashlib
def bucket(user_id, salt, n_buckets):
h = hashlib.blake2b(f"{salt}:{user_id}".encode(), digest_size=8).digest()
return int.from_bytes(h, "big") % n_buckets
```
### Class-balanced PyTorch sampler
```python
from torch.utils.data import WeightedRandomSampler
import numpy as np
def balanced_sampler(labels):
counts = np.bincount(labels)
weights = 1.0 / counts[labels]
return WeightedRandomSampler(weights, len(labels), replacement=True)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Population homogeneous | SRS |
| Subgroup variance 다름 | Stratified |
| Geographic cost 제약 | Cluster / Multistage |
| Streaming / unknown size | Reservoir |
| Heavy-tail Bayes posterior | NUTS / HMC |
| Sequential filtering | SMC / Particle Filter |
| Class imbalance training | Weighted / Balanced sampler |
**기본값**: training 은 stratified split, eval 은 i.i.d. test set, Bayes 는 NUTS, RLHF 는 task-stratified preference sampling.
## 🔗 Graph
- 부모: [[Statistics]] · [[Probability-Theory-Foundations]]
- 변형: [[Monte-Carlo-Integration]] · [[Particle-Filter-Algorithms]]
- 응용: [[Reinforcement_Learning_Fundamentals]] · [[Information Retrieval (IR)]]
- Adjacent: [[Posterior-and-Prior-Probability]] · [[Statistical-Power]]
## 🤖 LLM 활용
**언제**: dataset construction, eval design, RLHF/RLAIF preference collection, posterior inference, Monte-Carlo estimation 의 framing 때.
**언제 X**: full-population accessible (census), deterministic computation 으로 충분한 case.
## ❌ 안티패턴
- **Convenience sampling 으로 production decision**: 매 selection bias 직격탄.
- **stratified 변수 leakage**: stratify-by-target 후 train/test split 시 target 정보 누설.
- **MCMC 의 single-chain 만 신뢰**: 매 multi-chain + R-hat / ESS 검증 필수.
- **Reservoir sampling 의 reproducibility 무시**: seed pin 안 하면 매 재현 불가.
## 🧪 검증 / 검토
- Verified (Lohr 2021 "Sampling: Design and Analysis"; Gelman BDA3 ch.1012; NumPyro docs 0.16).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — probability/non-probability/MCMC families, alias-method/NUTS/reservoir patterns, RLHF context |