주성분분석은 보통 압축 기법으로 소개됩니다. 상관관계가 있는 변수 여럿을 받아 정보 대부분을 유지하는 소수의 무상관 변수를 만들어 낸다고요. 맞는 설명이지만 PCA를 제대로 이해할 이유를 놓칩니다.
Principal Component Analysis is usually introduced as compression: take many correlated variables, produce a few uncorrelated ones that retain most of the information. That is accurate, and it undersells why PCA is worth understanding properly.
더 쓸모 있는 설명은 이렇습니다. PCA는 데이터가 실제로 변하는 방향을 찾아 줍니다. 고차원 데이터셋 대부분은 사실 고차원이 아닙니다. 변수들이 함께 움직이고 실질적으로 독립적인 차원의 수는 열 개수보다 훨씬 적습니다. PCA는 그 수를 잽니다.
The more useful framing: PCA finds the directions in which your data actually varies. Most high-dimensional datasets are not really high-dimensional — the variables move together, and the effective number of independent dimensions is far smaller than the column count. PCA measures that.
기하학적으로 무슨 일이 일어나는가What it does, geometrically
p차원 공간에 점구름이 있다고 상상해 봅시다. PCA가 묻는 질문은 이렇습니다. 이 구름이 가장 넓게 퍼진 방향은 어디인가? 그게 첫 번째 주성분입니다. 다음으로, 그 방향을 제외했을 때 남은 퍼짐이 가장 큰 수직 방향은? 그게 두 번째입니다. 이렇게 계속됩니다.
Picture a cloud of points in p dimensions. PCA asks: along which direction is the cloud most spread out? That is the first principal component. Then, given that one, which perpendicular direction carries the most remaining spread? That is the second. And so on.
결과는 좌표계의 회전입니다. 새 축들은 담고 있는 분산의 크기 순으로 정렬됩니다. 회전 자체에서는 아무것도 잃지 않습니다. p개의 성분은 데이터를 정확히 기술합니다. 압축은 뒤쪽 성분을 버리는 데서 나옵니다. 근거는 분산이 작은 방향에는 정보가 적다는 것입니다.
The result is a rotation of the coordinate system into axes ordered by how much variance each carries. Nothing is lost in the rotation itself — p components describe the data exactly. The compression comes from discarding the later components, on the argument that directions with little variance carry little information.
계산상으로 성분은 공분산행렬의 고유벡터이고 고유값은 각 방향의 분산입니다. 실제로는 공분산행렬을 만들지 않고 특이값분해로 계산합니다. 수치적으로 훨씬 안정적이기 때문입니다.
Mechanically the components are eigenvectors of the covariance matrix, and their eigenvalues are the variance along each. In practice it is computed by singular value decomposition rather than by forming the covariance matrix, because SVD is numerically better behaved.
해석은 두 가지 양에 실려 있습니다.
Two quantities carry the interpretation.
- 설명분산비율. 각 성분이 담는 전체 분산의 비율입니다. 누적값을 보면 원하는 충실도를 얻으려면 성분이 몇 개 필요한지 알 수 있습니다.
- 적재량. 각 원변수가 각 성분에 얼마나 기여하는지입니다. 해석은 여기 삽니다. 어떤 성분이 의미가 있으려면 그 적재량이 일관된 이야기를 들려줘야 합니다.
- Explained variance ratio. The share of total variance on each component. The cumulative version tells you how many components you need for a given fidelity.
- Loadings. How much each original variable contributes to each component. Interpretation lives here — a component is only meaningful if its loadings tell a coherent story.
모두가 건너뛰는 단계The step everyone skips
이 방법은 분산이 최대인 방향을 찾고 분산은 단위에 의존합니다. 소득을 천 원 단위가 아니라 원 단위로 재면 그 분산은 백만 배가 됩니다. 그러면 첫 번째 주성분은 거의 전적으로 소득이 됩니다. 소득이 중요해서가 아니라 숫자가 커서입니다.
The method finds directions of maximum variance, and variance depends on units. Measure income in won rather than thousands of won and its variance grows by a factor of a million. The first principal component will then be almost entirely income — not because it is important, but because its numbers are large.
해법은 PCA를 돌리기 전에 모든 변수를 단위분산으로 표준화하는 것입니다. 공분산행렬 대신 상관행렬로 PCA를 돌리는 것과 같습니다. 이게 기본값이어야 합니다. 예외는 모든 변수가 이미 같은 의미 있는 단위이고 상대적 분산 자체가 실질적으로 흥미로운 경우뿐입니다. 픽셀 강도나 같은 양의 반복 측정 같은 것들입니다.
The fix is to standardise every variable to unit variance before running PCA, which is equivalent to running PCA on the correlation matrix rather than the covariance matrix. This should be the default. The exception is when all variables are already in the same meaningful units and their relative variances are substantively interesting — pixel intensities, or repeated measures of the same quantity.
이걸 틀려도 오류는 나지 않습니다. 그럴듯해 보이는데 사실은 단위 선택 말고 아무것도 담지 않은 성분이 나올 뿐입니다.
Getting this wrong does not raise an error. It produces components that look plausible and encode nothing but your choice of units.
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
# three variables that move together, plus one loud but uninformative column
signal = rng.normal(size=(500, 1))
X = np.hstack([
signal + rng.normal(scale=0.3, size=(500, 1)),
signal + rng.normal(scale=0.3, size=(500, 1)),
signal + rng.normal(scale=0.3, size=(500, 1)),
rng.normal(scale=1000, size=(500, 1)), # same information, larger unit
])
raw = PCA().fit(X)
scaled = make_pipeline(StandardScaler(), PCA()).fit(X)
print("unscaled :", np.round(raw.explained_variance_ratio_, 3))
print("scaled :", np.round(scaled[-1].explained_variance_ratio_, 3))unscaled : [1. 0. 0. 0. ]
scaled : [0.741 0.252 0.005 0.002]
표준화하지 않으면 첫 성분이 분산의 100%를 "설명"합니다. 그 성분은 잡음 열 하나입니다. 표준화하면 실제 구조가 드러납니다. 함께 움직이는 세 변수가 첫 성분에 모이고 나머지는 잔여입니다.
Unscaled, the first component "explains" 100% of the variance — and that component is a single noise column. Scaled, the real structure appears: the three variables that move together collapse onto the first component and the rest is residual.
PCA가 아닌 것What PCA is not
PCA에는 자주 요구되지만 할 수 없는 일들이 있습니다. 한계를 정확히 아는 편이 낫습니다.
PCA is routinely asked to do things it cannot. Worth being precise about the limits.
- 선형입니다. 성분은 원변수의 선형결합입니다. 휘어진 다양체 위에 놓인 데이터 — 고전적인 스위스롤 — 는 어떤 회전으로도 펴지지 않습니다. 이 한계가 정확히 다양체 학습 편의 동기입니다.
- 분산은 중요도가 아닙니다. PCA는 분산 순으로 방향을 정렬합니다. 이건 예측변수에 대한 진술이지 타깃에 대해서는 아무 말도 하지 않습니다. 분산이 작은 방향이 결과를 예측하는 방향일 수 있습니다. PCA 회귀가 때때로 평범한 회귀보다 못한 이유이고 타깃을 쓰는 부분최소제곱이 존재하는 이유입니다.
- 성분은 대개 해석되지 않습니다. 하나의 성분은 모든 원변수의 가중 혼합입니다. 가끔 깔끔한 의미가 붙지만 대개는 아닙니다. 그래도 이름을 붙이고 싶은 유혹은 참는 편이 낫습니다. 해석 가능성이 목표라면 희소 PCA나 요인분석이 더 적합합니다.
- 변수 선택이 아닙니다. PCA는 기존 변수 전부로 만든 새 변수를 내놓습니다. 성분을 계산하려면 여전히 원변수를 모두 측정해야 합니다. 일부 변수의 수집을 그만두는 게 목적이라면 PCA는 도움이 되지 않습니다. 정규화 회귀의 LASSO가 그 일을 합니다.
- It is linear. Components are linear combinations of the original variables. Data lying on a curved manifold — the classic Swiss roll — cannot be unrolled by any rotation. That limitation is exactly what motivates manifold learning.
- Variance is not importance. PCA orders directions by variance, which is a statement about the predictors and says nothing about the target. A low-variance direction can be the one that predicts your outcome. This is why PCA regression sometimes underperforms plain regression, and why partial least squares — which does use the target — exists.
- Components are usually not interpretable. A component is a weighted mixture of every original variable. Sometimes that mixture has a clean meaning; often it does not, and naming it anyway is a temptation worth resisting. If interpretability is the goal, sparse PCA or factor analysis are better suited.
- It is not feature selection. PCA produces new variables built from all the old ones. You still need to measure every original variable to compute them. If the goal is to stop collecting some variables, PCA does not help — LASSO in regularised regression does.
성분을 몇 개 남길 것인가How many components to keep
유일한 정답은 없고 보통 쓰는 기준은 넷입니다.
There is no single correct answer. Four common criteria.
| 기준 | 내용과 한계 |
|---|---|
| 누적분산 임계값 | 80~95%에 도달할 만큼 남깁니다. 단순하고 임의적이며 압축이 목적이면 충분합니다. |
| 스크리 도표의 팔꿈치 | 고유값을 순서대로 그리고 곡선이 평평해지는 지점을 찾습니다. 주관적이지만 대체로 명확합니다. |
| Kaiser 규칙 | 표준화 데이터에서 고유값이 1을 넘는 성분만 남깁니다. 널리 쓰이고 너무 많이 남기는 경향이 있습니다. |
| 교차검증 | PCA가 하류 모형에 들어간다면 그 모형의 표본 외 성능으로 고릅니다. 실제 목적함수에 연결된 유일한 기준입니다. |
| Criterion | What it does, and its limits |
|---|---|
| Cumulative variance | Keep enough to reach 80-95%. Simple, arbitrary, and fine for compression. |
| Scree plot elbow | Plot eigenvalues in order and look for where the curve flattens. Subjective but often clear. |
| Kaiser rule | On standardised data, keep components with eigenvalue above 1. Widely used and known to over-retain. |
| Cross-validation | If PCA feeds a downstream model, choose by that model out-of-sample performance. The only criterion tied to the actual objective. |
하류 작업이 있다면 마지막 기준을 쓰십시오. 나머지는 그런 작업이 없을 때의 대용입니다.
If a downstream task exists, use the last one. The others are proxies for when it does not.
실무에서In practice
- 표준화하십시오. 특별한 이유가 없다면.
StandardScaler다음에PCA를 두는 파이프라인을 써서 스케일러가 훈련 폴드에서만 적합되게 하십시오. 분할 전에 전체 데이터로 PCA를 적합하면 테스트 정보가 성분에 새어 들어갑니다. 교차검증 편에서 다룬 누출과 같은 것이고 똑같이 눈에 보이지 않습니다. - 하류로 넘기기 전에 설명분산을 확인하십시오. 변수 100개짜리 데이터의 첫 10개 성분이 분산의 95%를 설명한다면 구조가 강하고 PCA가 실제로 일을 합니다. 95%에 80개가 필요하다면 변수들이 거의 독립이고 PCA가 줄 것이 별로 없습니다.
- 이상치를 조심하십시오. 분산은 제곱량이므로 극단값 하나가 첫 성분을 통째로 지배할 수 있습니다. 성분 점수에 외따로 떨어진 점이 있는지 살펴보십시오. 오염이 실제 우려라면 로버스트 PCA 변형이 있습니다.
- 시각화용 PCA는 첫인상이지 결론이 아닙니다. 50차원 데이터의 두 성분은 그림자를 보여 줍니다. 보이는 군집이 투영의 산물일 수 있고 존재하는 군집이 투영에 가려질 수 있습니다. 48개 차원을 버리지 않는 방법으로 확인하십시오.
- 백색화는 문제를 바꿉니다.
whiten=True는 성분을 단위분산으로 재조정합니다. 어떤 알고리즘에는 도움이 되고 PCA를 의미 있게 만들었던 분산 순서를 파괴합니다. 어느 쪽을 원하는지 알고 쓰십시오. - 아주 큰 데이터에는 증분 또는 무작위 PCA를 쓰십시오.
IncrementalPCA는 메모리에 안 들어가는 데이터를 배치로 처리하고svd_solver="randomized"는 선두 성분만 필요할 때 훨씬 빠릅니다.
- Standardise, unless you have a specific reason not to. Use a pipeline with
StandardScalerbeforePCAso the scaler fits on training folds only. Fitting PCA on the full dataset before splitting leaks test information into the components — the same leak as in the cross-validation post, and just as invisible. - Check the explained variance before trusting anything downstream. If the first ten components of a hundred-variable dataset explain 95%, your data has strong structure and PCA is doing real work. If you need eighty components for 95%, the variables are close to independent and PCA has little to offer.
- Watch for outliers. Variance is a squared quantity, so a single extreme point can dominate the first component entirely. Inspect the component scores for isolated points; robust PCA variants exist when contamination is a real concern.
- PCA for visualisation is a first look, not a conclusion. Two components of a fifty-dimensional dataset show you a shadow. Clusters that appear may be projection artefacts, and clusters that exist may be hidden. Confirm any structure with a method that does not throw away 48 dimensions.
- Whitening changes the downstream problem.
whiten=Truerescales components to unit variance, which helps some algorithms and destroys the variance ordering that made PCA meaningful. Know which one you want. - For very large data, use incremental or randomised PCA.
IncrementalPCAprocesses in batches when the data does not fit in memory, andsvd_solver="randomized"is dramatically faster when you only need the leading components.
어디서 마주치게 되는가Where this shows up
- 금융. 금리 기간구조는 세 성분 — 수준, 기울기, 곡률 — 으로 놀랍도록 잘 설명됩니다. 이 셋이 모든 만기에 걸친 변동의 약 95%를 담습니다. 고차원 데이터가 사실은 저차원이라는 가장 깨끗한 실제 사례이고 채권 리스크 관리의 상당 부분이 여기 기대고 있습니다.
- 다중공선성. 회귀변수들이 강하게 상관되면 OLS 계수가 불안정해집니다. PCA 회귀가 한 가지 대응이지만 대개는 원변수와 그 해석을 유지하는 능형회귀가 더 낫습니다.
- 이미지와 신호 압축. 고유얼굴은 PCA 위에 바로 지어진 초기 얼굴인식 방법이었습니다.
- 유전체학. 유전 데이터의 집단 구조가 첫 몇 성분에 워낙 일관되게 나타나서 유전형 데이터의 PCA 도표가 지리 지도를 재현할 정도입니다.
- Finance. The term structure of interest rates is famously well described by three components — level, slope and curvature — together explaining around 95% of the variation across all maturities. One of the cleanest real examples of high-dimensional data having low effective dimension, and it underpins a great deal of fixed income risk management.
- Multicollinearity. When regressors are highly correlated, OLS coefficients become unstable. PCA regression is one response, though ridge regression is usually the better one because it keeps the original variables and their interpretation.
- Image and signal compression. Eigenfaces were an early face recognition method built directly on PCA.
- Genomics. Population structure in genetic data shows up in the first few components so reliably that PCA plots of genotype data reproduce geographic maps.
한 세기가 넘은 방법인데도 PCA가 여전히 알아 둘 값어치가 있는 이유는, 이 데이터의 차원이 실제로 몇이냐는 질문이 거의 모든 다른 모델링 결정보다 앞에 오기 때문입니다.
The reason PCA remains worth knowing despite being over a century old is that the question it answers — how many dimensions does this data really have — comes before almost every other modelling decision.