[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,62 +2,224 @@
|
||||
id: wiki-2026-0508-factor-analysis
|
||||
title: Factor Analysis
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [STAT-FACTOR-001]
|
||||
aliases: [FA, EFA, CFA, PCA-vs-FA, latent factor, Spearman g, Big Five]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: ["Statistics|[Statistics", machine-learning, factor-Analysis, latent-variables, Dimensionality-Reduction]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [statistics, factor-analysis, latent-variable, dimensionality-reduction, psychometrics, sem]
|
||||
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: Python / R
|
||||
framework: factor_analyzer / lavaan / scikit-learn
|
||||
---
|
||||
|
||||
# Factor Analysis (요인 분석)
|
||||
# Factor Analysis
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "수많은 겉모습 속에 숨겨진 공통의 근원을 찾아라" — 관측된 여러 변수들 사이의 상관관계를 분석하여, 배후에 존재하는 소수의 잠재 변수(Latent Variables) 혹은 요인(Factors)을 추출하는 통계적 기법.
|
||||
## 매 한 줄
|
||||
> **"매 latent factor 의 의 의 observed variable 의 explain"**. 매 EFA (exploratory) → 매 structure 의 discover. 매 CFA (confirmatory) → 매 hypothesis 의 test. 매 PCA 와 다름 — 매 FA 의 latent + error decompose. 매 famous: 매 Spearman g, Big Five.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** 눈에 보이는 데이터(Manifest Variables)의 요동이 사실은 보이지 않는 핵심 동인(Latent Factors)에 의해 결정된다고 가정하고 그 구조를 파악하는 구조적 해석 패턴.
|
||||
- **주요 목적:**
|
||||
- **Data Reduction:** 수많은 변수를 소수의 요인으로 압축하여 효율성 증대.
|
||||
- **Structure Discovery:** 변수들 간의 복잡한 관계 네트워크 파악.
|
||||
- **Scaling:** 추상적인 개념(예: 지능, 성격, 서비스 만족도)을 측정 가능한 지표로 변환.
|
||||
- **작동 원리:** 변수들 간의 공통 분산(Common Variance)을 극대화하는 축을 탐색.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** PCA(주성분 분석)와 혼동하기 쉬우나, PCA는 정보 요약에 집중하고 요인 분석은 데이터가 생성된 '인과적 구조'를 설명하는 데 집중한다는 차이점이 명확해짐.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트의 성능 지표(응답 속도, 정확도, 토큰 사용량 등)를 분석할 때, 이들을 결정짓는 잠재 요인(예: 하드웨어 성능, 모델 복잡도, 네트워크 지연)을 분리하기 위해 요인 분석 기법을 활용함.
|
||||
### 매 model
|
||||
```
|
||||
X = ΛF + ε
|
||||
```
|
||||
- X: 매 observed (n×p).
|
||||
- F: 매 factors (n×k), latent.
|
||||
- Λ: 매 loadings (p×k).
|
||||
- ε: 매 unique error.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Principal-Component-Analysis|Principal-Component-Analysis]]-PCA, [[Dimensionality-Reduction|Dimensionality-Reduction]], [[Exploratory-Data-Analysis|Exploratory-Data-Analysis]], Un[[Supervised-Learning-Foundations|Supervised-Learning-Foundations]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Factor-Analysis.md
|
||||
### 매 PCA vs FA
|
||||
- **PCA**: 매 variance 의 maximize, 매 component = linear combo.
|
||||
- **FA**: 매 covariance 의 explain, 매 latent factor + error.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 EFA vs CFA
|
||||
- **EFA**: 매 # factor 의 unknown.
|
||||
- **CFA**: 매 hypothesis 의 confirm (SEM).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 step (EFA)
|
||||
1. **KMO + Bartlett**: 매 factorability.
|
||||
2. **# factor**: 매 scree, parallel analysis, MAP.
|
||||
3. **Extract**: 매 PAF, ML.
|
||||
4. **Rotate**: 매 varimax (orthogonal), oblimin (oblique).
|
||||
5. **Interpret**.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
1. **Psychometrics**: 매 Big Five.
|
||||
2. **Marketing**: 매 brand perception.
|
||||
3. **Finance**: 매 risk factor.
|
||||
4. **Bioinfo**: 매 gene expression.
|
||||
5. **NLP**: 매 word factor.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
## 💻 패턴
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### Factorability check (Python)
|
||||
```python
|
||||
from factor_analyzer.factor_analyzer import calculate_kmo, calculate_bartlett_sphericity
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
chi_sq, p = calculate_bartlett_sphericity(df)
|
||||
print(f'Bartlett: chi2={chi_sq:.2f}, p={p:.4f}') # 매 p<0.05 OK
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
kmo_all, kmo_model = calculate_kmo(df)
|
||||
print(f'KMO: {kmo_model:.2f}') # 매 > 0.6 acceptable, > 0.8 great
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### Scree + parallel analysis
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from factor_analyzer import FactorAnalyzer
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
fa = FactorAnalyzer(rotation=None)
|
||||
fa.fit(df)
|
||||
ev, v = fa.get_eigenvalues()
|
||||
plt.plot(range(1, len(ev) + 1), ev, 'o-')
|
||||
plt.axhline(1, color='red', ls='--') # 매 Kaiser
|
||||
plt.title('Scree')
|
||||
plt.show()
|
||||
```
|
||||
|
||||
### EFA (varimax rotation)
|
||||
```python
|
||||
fa = FactorAnalyzer(n_factors=5, rotation='varimax').fit(df)
|
||||
loadings = pd.DataFrame(fa.loadings_, index=df.columns, columns=[f'F{i+1}' for i in range(5)])
|
||||
print(loadings.round(2))
|
||||
```
|
||||
|
||||
### Interpretation (high-loading items)
|
||||
```python
|
||||
def interpret_factors(loadings, threshold=0.4):
|
||||
for col in loadings.columns:
|
||||
items = loadings[loadings[col].abs() > threshold].index.tolist()
|
||||
print(f'{col}: {items}')
|
||||
```
|
||||
|
||||
### CFA (lavaan-style in semopy)
|
||||
```python
|
||||
from semopy import Model
|
||||
desc = """
|
||||
Conscientiousness =~ orderly + reliable + careful
|
||||
Openness =~ creative + curious + imaginative
|
||||
Extraversion =~ sociable + assertive + energetic
|
||||
Conscientiousness ~~ Openness
|
||||
"""
|
||||
model = Model(desc)
|
||||
model.fit(df)
|
||||
print(model.inspect())
|
||||
```
|
||||
|
||||
### Item difficulty (loading magnitude)
|
||||
```python
|
||||
def factor_quality(loadings):
|
||||
return {
|
||||
'avg_loading': loadings.abs().mean(),
|
||||
'cross_loadings': (loadings.abs() > 0.4).sum(axis=1).gt(1).sum(),
|
||||
'low_communality': (loadings.abs().pow(2).sum(axis=1) < 0.3).sum(),
|
||||
}
|
||||
```
|
||||
|
||||
### Reliability (Cronbach α)
|
||||
```python
|
||||
def cronbach_alpha(items):
|
||||
"""매 매 factor 의 internal consistency."""
|
||||
k = items.shape[1]
|
||||
return k / (k - 1) * (1 - items.var(ddof=1).sum() / items.sum(axis=1).var(ddof=1))
|
||||
```
|
||||
|
||||
### Big Five inventory
|
||||
```python
|
||||
BIG_FIVE_ITEMS = {
|
||||
'Openness': ['imaginative', 'curious', 'creative', 'broad_interest'],
|
||||
'Conscientiousness': ['organized', 'thorough', 'reliable', 'efficient'],
|
||||
'Extraversion': ['outgoing', 'energetic', 'assertive', 'talkative'],
|
||||
'Agreeableness': ['kind', 'trusting', 'cooperative', 'forgiving'],
|
||||
'Neuroticism': ['anxious', 'moody', 'stress', 'worry'],
|
||||
}
|
||||
```
|
||||
|
||||
### Number of factors (parallel analysis)
|
||||
```python
|
||||
def parallel_analysis(df, n_iter=100):
|
||||
"""매 randomly permuted data 의 eigen 의 95th percentile."""
|
||||
n, p = df.shape
|
||||
rand_eigs = []
|
||||
for _ in range(n_iter):
|
||||
rand = np.random.normal(0, 1, (n, p))
|
||||
ev = np.linalg.eigvalsh(np.corrcoef(rand.T))[::-1]
|
||||
rand_eigs.append(ev)
|
||||
threshold = np.percentile(rand_eigs, 95, axis=0)
|
||||
actual = np.linalg.eigvalsh(np.corrcoef(df.T))[::-1]
|
||||
return np.sum(actual > threshold)
|
||||
```
|
||||
|
||||
### MIMIC / SEM
|
||||
```python
|
||||
desc = """
|
||||
# 매 measurement
|
||||
Latent =~ x1 + x2 + x3
|
||||
# 매 structural
|
||||
Latent ~ age + sex
|
||||
"""
|
||||
```
|
||||
|
||||
### Score factor (after fit)
|
||||
```python
|
||||
factor_scores = fa.transform(df)
|
||||
df['factor_1'] = factor_scores[:, 0]
|
||||
```
|
||||
|
||||
### Bayesian FA (PyMC)
|
||||
```python
|
||||
import pymc as pm
|
||||
with pm.Model() as bfa:
|
||||
L = pm.Normal('L', 0, 1, shape=(p, k))
|
||||
F = pm.Normal('F', 0, 1, shape=(n, k))
|
||||
sigma = pm.HalfNormal('sigma', 1, shape=p)
|
||||
pm.Normal('x', mu=F @ L.T, sigma=sigma, observed=X)
|
||||
trace = pm.sample()
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Discover structure | EFA + parallel analysis |
|
||||
| Test hypothesis | CFA (semopy / lavaan) |
|
||||
| Pure dim reduction | PCA |
|
||||
| Latent + measurement error | FA |
|
||||
| Psychometrics | EFA → CFA |
|
||||
| Causal latent | SEM (MIMIC) |
|
||||
|
||||
**기본값**: 매 EFA → 매 # factor (parallel) → 매 oblimin rotation → 매 CFA hypothesis confirm + 매 reliability check.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Statistics]] · [[Multivariate]]
|
||||
- 변형: [[EFA]] · [[CFA]] · [[SEM]]
|
||||
- 응용: [[Big-Five]] · [[Psychometrics]] · [[Risk-Factor-Models]]
|
||||
- Adjacent: [[PCA]] · [[Latent-Variable-Model]] · [[Cronbach-Alpha]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 questionnaire. 매 latent construct.
|
||||
**언제 X**: 매 pure dim reduction (use PCA).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **PCA = FA confusion**: 매 different.
|
||||
- **No factorability check**: 매 garbage in.
|
||||
- **Extract too many factors**: 매 noise.
|
||||
- **No rotation interp**: 매 unintepretable.
|
||||
- **No reliability**: 매 factor 의 trust.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Spearman 1904, Thurstone, Costa & McCrae Big Five).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-04-26 | STAT-FACTOR auto |
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — EFA / CFA + 매 KMO / scree / varimax / Cronbach code |
|
||||
|
||||
Reference in New Issue
Block a user