Tech PostsTech Posts
머신러닝Machine Learning · 21 / 24
21 머신러닝Machine Learning

회전만으로는 펴지지 않는 것What No Rotation Will Ever Straighten

PCA는 회전만 할 수 있습니다. 데이터의 구조가 휘어 있으면 어떤 회전으로도 펼 수 없습니다.PCA can only rotate. If the structure in your data is curved, no rotation will straighten it.

PCA는 회전만 할 수 있습니다. 데이터의 구조가 휘어 있으면 어떤 회전으로도 펴지지 않습니다.

PCA can only rotate. If the structure in your data is curved, no rotation will straighten it.

표준 예시는 스위스롤입니다. 3차원 공간에서 둘둘 말린 2차원 시트 위에 점들이 놓여 있습니다. 내재적 구조는 평평한 시트, 즉 2차원인데 PCA는 3차원 덩어리를 보고 시트를 되찾지 못합니다. 펴는 것은 선형 연산이 아니기 때문입니다.

The standard illustration is the Swiss roll: points lying on a two-dimensional sheet that has been rolled up in three dimensions. The intrinsic structure is a flat sheet — two dimensions — but PCA sees a three-dimensional blob and cannot recover it, because unrolling is not a linear operation.

다양체 학습은 그것을 할 수 있는 방법군입니다. 다양체 가설이라 불리는 전제는, 고차원 데이터가 그 공간에 박힌 저차원 곡면 위나 그 근처에 놓이는 경우가 많다는 것입니다. 회전하는 얼굴 사진들은 기술적으로 픽셀 수만큼 차원이 있는 공간의 점이지만 실제로는 회전각이라는 모수 하나가 지배하는 경로를 그립니다. 백만 차원짜리 외투를 입은 1차원 데이터입니다.

Manifold learning is the family of methods that can. The premise, sometimes called the manifold hypothesis, is that high-dimensional data often lies on or near a low-dimensional surface embedded in that space. Images of a face rotating are technically points in a space with as many dimensions as pixels, but they trace a path governed by one parameter — the rotation angle. The data is one-dimensional wearing a million-dimensional coat.

핵심 구분: 측지거리 대 유클리드거리The key distinction: geodesic versus Euclidean

방법들은 주로 그 표면 거리를 어떻게 근사하는지에서 갈립니다.

The methods differ mainly in how they approximate that surface distance.

  • Isomap은 이웃 그래프를 만들고 — 각 점을 k개의 최근접 이웃과 연결 — 그래프 최단경로를 측지거리로 씁니다. 그다음 그 거리에 고전적 다차원척도법을 돌립니다. 개념적으로 가장 깔끔하고 전역 구조를 잘 보존합니다.
  • 국소 선형 임베딩(LLE)은 다른 길을 갑니다. 각 점을 이웃들의 가중조합으로 표현하고 그 가중치를 보존하는 저차원 배치를 찾습니다. 전역 거리를 아예 계산하지 않고 겹치는 국소 조각들로부터 전역 구조가 떠오르게 합니다.
  • 다차원척도법(MDS)은 쌍별 거리를 최대한 보존하는 저차원 배치를 찾습니다. 유클리드거리에 대한 계량 MDS는 본질적으로 PCA이고 값어치는 비유클리드 거리를 쓸 때 나옵니다. Isomap이 하는 일이 정확히 그것입니다.
  • t-SNE와 UMAP은 시각화의 현대적 주력입니다. 거리를 이웃일 확률로 바꾸고 그 확률에 맞는 저차원 배치를 찾습니다. 둘 다 군집 구조를 드러내는 데 탁월하고 둘 다 심각한 단서가 붙습니다.
  • Isomap builds a neighbourhood graph — each point connected to its k nearest neighbours — and takes the shortest path through the graph as the geodesic distance, then runs classical multidimensional scaling on those distances. Conceptually the cleanest of the family, and it preserves global structure well.
  • Locally Linear Embedding (LLE) takes a different route: each point is expressed as a weighted combination of its neighbours, then a low-dimensional configuration is found that preserves those same weights. It never computes global distances at all; global structure emerges from overlapping local patches.
  • Multidimensional scaling (MDS) finds a low-dimensional layout preserving pairwise distances as well as possible. Metric MDS on Euclidean distances is essentially PCA; the value comes from using a non-Euclidean distance, which is exactly what Isomap does.
  • t-SNE and UMAP are the modern workhorses for visualisation. Both convert distances into probabilities of being neighbours and find a low-dimensional layout matching those probabilities. Both are excellent at revealing cluster structure and both come with serious caveats.
python
import numpy as np
from sklearn.datasets import make_swiss_roll
from sklearn.decomposition import PCA
from sklearn.manifold import Isomap, LocallyLinearEmbedding
import matplotlib.pyplot as plt

X, colour = make_swiss_roll(n_samples=2_000, noise=0.05, random_state=0)

methods = {
    "PCA (linear)":  PCA(n_components=2),
    "Isomap":        Isomap(n_neighbors=12, n_components=2),
    "LLE":           LocallyLinearEmbedding(n_neighbors=12, n_components=2),
}

fig, axes = plt.subplots(1, 3, figsize=(15, 4))
for ax, (name, model) in zip(axes, methods.items()):
    Z = model.fit_transform(X)
    ax.scatter(Z[:, 0], Z[:, 1], c=colour, cmap="Spectral", s=6)
    ax.set_title(name); ax.set_xticks([]); ax.set_yticks([])
색은 롤을 따라간 참 위치입니다. PCA에서는 색이 섞이고 Isomap에서는 매끄러운 그러데이션이 됩니다.Colour is the true position along the roll. In PCA the colours mix; in Isomap they become a smooth gradient.

PCA 패널에서는 롤의 먼 부분들이 겹쳐 색이 섞입니다. Isomap 패널에서는 색이 매끄러운 그러데이션이 됩니다. 시트가 펴진 것입니다.

In the PCA panel, distant parts of the roll overlap and the colours mix. In the Isomap panel the colours form a smooth gradient — the sheet has been unrolled.

모든 것을 결정하는 모수The parameter that decides everything

여기 모든 방법에서 이웃 크기 — Isomap과 LLE의 k, t-SNE의 perplexity, UMAP의 n_neighbors — 가 가장 결과를 좌우하는 선택입니다.

For every method here, the neighbourhood size — k in Isomap and LLE, perplexity in t-SNE, n_neighbors in UMAP — is the single most consequential choice.

  • 너무 작으면 이웃 그래프가 연결이 끊긴 조각들로 쪼개집니다. 그러면 알고리즘이 각 조각을 독립적으로 임베딩하고 조각 사이의 관계는 무의미해집니다.
  • 너무 크면 이웃이 곡률을 가로질러 롤을 관통하는 지름길을 만듭니다. 유클리드거리로 되돌아간 것이고 방법이 PCA 쪽으로 퇴화합니다.
  • Too small and the neighbourhood graph fragments into disconnected components. The algorithm then embeds each piece independently and the relationships between them are meaningless.
  • Too large and neighbourhoods span the curvature, short-circuiting across the roll. You are back to Euclidean distance and the method degenerates toward PCA.

답을 모르는 상태에서 원리적으로 고르는 방법은 없습니다. 정직한 접근은 여러 값을 돌려 보고 보이는 구조가 값에 걸쳐 안정적인지 확인하는 것입니다. 한 설정에서 나타났다가 다음 설정에서 사라지는 구조는 인공물입니다.

There is no principled way to choose it without knowing the answer. The honest approach is to run a range of values and check whether the structure you see is stable across them. Structure that appears at one setting and vanishes at the next is an artefact.

t-SNE와 UMAP 그림이 뜻하지 않는 것What t-SNE and UMAP plots do not mean

이 그림들이 워낙 널리 만들어지고 널리 과잉 해석되므로 따로 절을 둘 값어치가 있습니다.

This deserves its own section because these plots are so widely produced and so widely over-read.

  • 군집 사이의 거리도 대체로 무의미합니다. t-SNE 그림에서 멀리 떨어진 두 군집이 가까운 두 군집보다 반드시 더 다르지는 않습니다. 이 방법들은 국소 이웃 보존을 최적화하고 전역 기하는 명시적으로 희생합니다. UMAP은 t-SNE보다 낫다고 주장하지만 그 보장은 약합니다.
  • 보이는 군집이 인공물일 수 있습니다. t-SNE는 어떤 perplexity 설정에서 순수한 잡음으로부터 시각적으로 설득력 있는 군집을 만들어 냅니다. 항상 셔플한 데이터에 돌린 결과와 비교하십시오.
  • 임베딩은 재사용할 수 있는 변환이 아닙니다. t-SNE에는 구성상 새 점에 대한 transform 메서드가 없습니다. UMAP에는 근사적으로 있습니다. 어느 쪽도 지도학습 파이프라인 안의 전처리 단계로 적합하지 않습니다.
  • Distances between clusters are largely meaningless. Two clusters far apart on a t-SNE plot are not necessarily more different than two that are close. These methods optimise local neighbourhood preservation and explicitly sacrifice global geometry — UMAP claims to do better, but the guarantee is weak.
  • Apparent clusters can be artefacts. t-SNE will produce visually convincing clusters from pure noise at some perplexity settings. Always compare against a run on shuffled data.
  • The embedding is not a transform you can reuse. t-SNE has no transform method for new points, by construction. UMAP has one, approximately. Neither is suitable as a preprocessing step inside a supervised pipeline.

올바른 용법은 탐색적입니다. 구조에 대한 가설을 세우고 통계적 보장이 있는 방법으로 검증하십시오.

The correct use is exploratory: form a hypothesis about structure, then verify it with a method that has statistical guarantees.

선형으로 충분할 때When linear is enough

다양체 방법은 PCA보다 비싸고 튜닝에 민감하며 해석하기 어렵습니다. 손을 뻗기 전에 PCA로 이미 되는지 확인하십시오. 첫 몇 성분이 분산 대부분을 설명하고 관심 대상을 분리한다면 곡률은 문제가 아니었습니다.

Manifold methods are more expensive, more sensitive to tuning, and harder to interpret than PCA. Before reaching for them, check whether PCA already works — if the first few components explain most of the variance and separate whatever you care about, curvature was not the problem.

빠른 진단은 차원을 늘려 가며 PCA와 Isomap의 잔차 분산을 비교하는 것입니다. Isomap 쪽이 훨씬 빨리 떨어지면 진짜 비선형 구조가 있습니다. 나란히 가면 데이터는 사실상 선형입니다.

A quick diagnostic is to compare the residual variance of PCA and Isomap across increasing dimensions. If Isomap drops much faster, there is genuine non-linear structure. If they track each other, the data is effectively linear.

실무에서In practice

  • PCA와 같은 이유로 피처를 먼저 스케일링하십시오. 이 방법들은 전부 거리에 의존하고 거리는 단위에 의존합니다. 단위가 큰 변수 하나가 모든 이웃 계산을 지배합니다.
  • 이웃 그래프가 연결되어 있는지 확인하십시오. Isomap과 LLE는 연결이 끊긴 그래프에서 조용히 실패합니다. sklearn이 경고를 내지만 놓치기 쉽고 그 결과 임베딩은 불완전한 정도가 아니라 무의미합니다.
  • t-SNE나 UMAP 전에 PCA로 줄이십시오. 수백 차원에서 직접 돌리는 건 느리고 잡음이 큽니다. 표준 관행은 PCA로 50성분 정도까지 줄인 다음 다양체 방법을 쓰는 것이고 t-SNE 문헌의 권장 기본값이지 요령이 아닙니다.
  • 시드를 고정하고 여러 번 돌리십시오. t-SNE와 UMAP은 확률적이고 실행마다 눈에 띄게 다른 배치를 냅니다. 시드에 따라 결론이 바뀐다면 그건 결론이 아니었습니다.
  • 복잡도를 주시하십시오. Isomap은 전체 쌍 최단경로가 필요해 대략 O(n² log n)입니다. 이 시리즈의 계산 효율 편이 직접 관련됩니다. 수만 점을 넘어가면 규모를 염두에 두고 설계된 UMAP을 쓰십시오.
  • 다양체 임베딩을 인과분석에 넣지 마십시오. 차원에 안정적인 의미가 없고 식별되지 않으며 난수 시드에 따라 바뀝니다. 이 방법들이 무엇을 위한 것이든 회귀의 통제변수를 만드는 용도는 아닙니다.
  • Scale features first, for the same reason as PCA. All of these depend on distances, and distances depend on units. A variable in a large unit dominates every neighbourhood computation.
  • Check that the neighbourhood graph is connected. Isomap and LLE fail quietly on disconnected graphs. sklearn will warn, but the warning is easy to miss and the resulting embedding is meaningless rather than merely imperfect.
  • Reduce with PCA before running t-SNE or UMAP. Running these directly on hundreds of dimensions is slow and noisy. Standard practice is PCA to around 50 components first, then the manifold method — a recommended default in the t-SNE literature, not a shortcut.
  • Set the random seed and run more than once. Both are stochastic and produce visibly different layouts across runs. If your conclusion changes between seeds, it was not a conclusion.
  • Watch the complexity. Isomap requires all-pairs shortest paths, roughly O(n² log n) — the computational efficiency post is directly relevant. Beyond tens of thousands of points, use UMAP, which was designed for scale.
  • Do not feed manifold embeddings into causal analysis. The dimensions have no stable meaning, they are not identifiable, and they change with the random seed. Whatever these methods are for, it is not producing controls for a regression.

단일세포 유전체학에서 세포 집단의 UMAP 그림은 이제 표준이고 위의 단서들이 그대로 적용됩니다. 군집 간 거리에서 방법이 뒷받침하지 않는 많은 것들이 읽혀 왔습니다. 이상 탐지에서는 학습된 다양체에서 먼 점이 구성상 이상치이고 여러 실용 시스템의 기반입니다. 오토인코더는 다른 이름의 다양체 학습입니다. 병목 층이 데이터의 저차원 좌표계를 학습합니다. 현대 표현학습이 대체로 이 아이디어에 모수를 더한 것이라는 점에서 연결을 알아 둘 값어치가 있습니다.

UMAP plots of cell populations are now standard in single-cell genomics, and the caveats above apply directly — a great deal has been read into inter-cluster distances that the method does not support. In anomaly detection, points far from the learned manifold are anomalies by construction, the basis of several practical systems. Autoencoders are manifold learning by another name: the bottleneck layer learns a low-dimensional coordinate system, and the connection is worth noticing because modern representation learning is largely this idea with more parameters.

다양체 가설은 딥러닝이 자연 이미지에서 애초에 작동하는 이유에 대한 가장 흔한 설명이기도 합니다. 가능한 모든 픽셀 배열의 공간은 상상하기 어려울 만큼 크지만 사진의 공간은 그 안의 비교적 작은 곡면이고 신경망이 배우는 것이 그 곡면입니다.

The manifold hypothesis is also the most common explanation for why deep learning works at all on natural images: the space of all possible pixel arrays is unimaginably large, but the space of photographs is a comparatively tiny surface within it, and that is the surface a network learns.