| 1 | import numpy as np |
| 2 | import torch |
| 3 | from deep_kmeans import LATENT_SIZE, Decoder, Encoder, cluster_acc, load_data |
| 4 | from scipy.optimize import linear_sum_assignment |
| 5 | from sklearn.cluster import KMeans as SklearnKMeans |
| 6 | from torch import nn |
| 7 | |
| 8 | torch.set_num_threads(1) # 작은 모델이라 스레드 하나가 오히려 빠르다 |
| 9 | device = torch.device("cpu") |
| 10 | train_x, test_x, test_y = load_data(device) |
| 11 | |
| 12 | # demo는 1분 안에 끝나야 하므로 학습 6,000장, 테스트 2,000장만 쓴다 |
| 13 | N_TRAIN, N_TEST, EPOCHS = 6000, 2000, 10 |
| 14 | train_x, test_x, test_y = train_x[:N_TRAIN], test_x[:N_TEST], test_y[:N_TEST] |
| 15 | |
| 16 | |
| 17 | def confusion(y_true: np.ndarray, y_pred: np.ndarray) -> np.ndarray: |
| 18 | """cluster_acc 안에서 만드는 표와 같은 것. w[i, j] = 군집 i에 들어간 숫자 j의 개수""" |
| 19 | d = max(y_pred.max(), y_true.max()) + 1 |
| 20 | w = np.zeros((d, d), dtype=np.int64) |
| 21 | np.add.at(w, (y_pred, y_true), 1) |
| 22 | return w |
| 23 | |
| 24 | |
| 25 | def print_table(w: np.ndarray, indent: str = " ") -> None: |
| 26 | print(f"{indent}숫자 |" + "".join(f"{j:>5}" for j in range(w.shape[1]))) |
| 27 | for i, row in enumerate(w): |
| 28 | print(f"{indent}군집 {i} |" + "".join(f"{v:>5}" for v in row)) |
| 29 | |
| 30 | |
| 31 | print("1) 손으로 만든 작은 예: 그림 9장, 숫자 3종류(0, 1, 2)") |
| 32 | y_true = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]) |
| 33 | y_pred = np.array([2, 2, 2, 0, 0, 0, 1, 1, 0]) |
| 34 | print(f" 실제 숫자 y_true : {y_true.tolist()}") |
| 35 | print(f" 군집 번호 y_pred : {y_pred.tolist()}") |
| 36 | print(" 같은 숫자끼리 거의 완벽하게 묶였다. 그런데 번호를 그대로 비교하면") |
| 37 | print( |
| 38 | f" (y_true == y_pred).mean() = {(y_true == y_pred).mean():.3f} ← 한 장도 안 맞은 것으로 나온다" |
| 39 | ) |
| 40 | print() |
| 41 | |
| 42 | print("2) 혼동 표: 행은 군집, 열은 실제 숫자") |
| 43 | w = confusion(y_true, y_pred) |
| 44 | print_table(w) |
| 45 | rows, cols = linear_sum_assignment(w, maximize=True) |
| 46 | print( |
| 47 | " 헝가리안 알고리즘이 고른 짝: " |
| 48 | + ", ".join(f"군집 {r} → 숫자 {c}" for r, c in zip(rows, cols)) |
| 49 | ) |
| 50 | print( |
| 51 | f" 짝지은 칸의 합 {' + '.join(str(w[r, c]) for r, c in zip(rows, cols))} = {w[rows, cols].sum()}" |
| 52 | ) |
| 53 | print(f" cluster_acc = {w[rows, cols].sum()} / {y_pred.size} = {cluster_acc(y_true, y_pred):.3f}") |
| 54 | print() |
| 55 | |
| 56 | print( |
| 57 | f"3) 진짜 데이터: MNIST 테스트 {N_TEST:,}장의 픽셀 784개에 보통의 K-평균(scikit-learn)을 돌린다" |
| 58 | ) |
| 59 | pixels = test_x.reshape(N_TEST, -1).numpy() |
| 60 | pred_pixel = SklearnKMeans(n_clusters=10, n_init=3, random_state=0).fit_predict(pixels) |
| 61 | w = confusion(test_y, pred_pixel) |
| 62 | print_table(w) |
| 63 | rows, cols = linear_sum_assignment(w, maximize=True) |
| 64 | print(" 짝: " + ", ".join(f"{r}→{c}" for r, c in zip(rows, cols)) + " (군집→숫자)") |
| 65 | print(f" {(test_y == pred_pixel).mean():.3f} ← 번호를 그대로 비교한 정확도") |
| 66 | print(f" {cluster_acc(test_y, pred_pixel):.3f} ← 짝을 맞춘 군집 정확도") |
| 67 | print() |
| 68 | |
| 69 | print("4) 같은 K-평균을 오토인코더의 잠재 변수 10개에 돌리면") |
| 70 | print(f" (3단계처럼 복원 손실만으로 학습. 학습 {N_TRAIN:,}장, {EPOCHS} 에폭, 시드 2)") |
| 71 | torch.manual_seed(2) |
| 72 | encoder, decoder = Encoder(LATENT_SIZE), Decoder(LATENT_SIZE) |
| 73 | optimizer = torch.optim.Adam([*encoder.parameters(), *decoder.parameters()], lr=1e-3) |
| 74 | for _ in range(EPOCHS): |
| 75 | for idx in torch.randperm(N_TRAIN).split(128): |
| 76 | x = train_x[idx] |
| 77 | loss = nn.functional.mse_loss(decoder(encoder(x)), x) |
| 78 | optimizer.zero_grad() |
| 79 | loss.backward() |
| 80 | optimizer.step() |
| 81 | with torch.no_grad(): |
| 82 | latents = encoder(test_x).numpy() |
| 83 | rec = nn.functional.mse_loss(decoder(encoder(test_x)), test_x).item() |
| 84 | pred_latent = SklearnKMeans(n_clusters=10, n_init=3, random_state=0).fit_predict(latents) |
| 85 | print(f" 테스트 복원 손실 {rec:.4f}, 잠재 변수 {latents.shape}") |
| 86 | print(f" 픽셀 공간 K-평균 (784차원) : 군집 정확도 {cluster_acc(test_y, pred_pixel):.3f}") |
| 87 | print(f" 잠재 공간 K-평균 ( 10차원) : 군집 정확도 {cluster_acc(test_y, pred_latent):.3f}") |