| 1 | """8.6 깊은 K-평균 알고리즘 (Deep K-Means) |
| 2 | |
| 3 | 합성곱 오토인코더와 K-평균을 한꺼번에 학습한다. 인코더가 만든 잠재 변수가 |
| 4 | "이미지를 복원할 수 있으면서(복원 손실) 군집 중심 근처에 모이도록(군집 손실)" 만든다. |
| 5 | 라벨 없이 학습한 뒤, 군집 번호와 실제 숫자를 헝가리안 알고리즘으로 짝지어 군집 정확도를 잰다. |
| 6 | |
| 7 | 실행: uv run python ch08_unsupervised/08_deep_kmeans.py |
| 8 | """ |
| 9 | |
| 10 | # %% |
| 11 | import matplotlib.pyplot as plt |
| 12 | import numpy as np |
| 13 | import torch |
| 14 | from scipy.optimize import linear_sum_assignment |
| 15 | from sklearn.manifold import TSNE |
| 16 | from torch import nn |
| 17 | from torchvision import datasets |
| 18 | |
| 19 | from ptintro import DATA_DIR, MODEL_DIR, QUICK, save_fig |
| 20 | |
| 21 | BATCH_SIZE = 128 |
| 22 | NUM_CLUSTERS = 10 |
| 23 | LATENT_SIZE = 10 |
| 24 | LAMBDA = 1e-3 # 군집 손실 가중치(alpha)의 최댓값 |
| 25 | CKPT_PATH = MODEL_DIR / "deep_kmeans.pth" |
| 26 | |
| 27 | |
| 28 | # %% |
| 29 | # 데이터 |
| 30 | def to_tensor_images(images: torch.Tensor) -> torch.Tensor: |
| 31 | """MNIST 원본 (N, 28, 28) uint8 → (N, 1, 28, 28) float, 0~1 범위""" |
| 32 | return images.unsqueeze(1).float() / 255 |
| 33 | |
| 34 | |
| 35 | def load_data(device: torch.device): |
| 36 | """(학습 이미지, 테스트 이미지, 테스트 라벨)을 돌려준다. |
| 37 | |
| 38 | 에폭을 여러 번 돌아야 하므로 MNIST 전체를 텐서 하나로 만들어 장치에 올려 둔다. |
| 39 | DataLoader로 매번 한 장씩 변환하는 것보다 훨씬 빠르다. 라벨은 평가할 때만 쓴다. |
| 40 | """ |
| 41 | trainset = datasets.MNIST(DATA_DIR, train=True, download=True) |
| 42 | testset = datasets.MNIST(DATA_DIR, train=False, download=True) |
| 43 | n_train, n_test = (2000, 1000) if QUICK else (len(trainset), len(testset)) |
| 44 | train_x = to_tensor_images(trainset.data[:n_train]).to(device) |
| 45 | test_x = to_tensor_images(testset.data[:n_test]).to(device) |
| 46 | test_y = testset.targets[:n_test].numpy() |
| 47 | return train_x, test_x, test_y |
| 48 | |
| 49 | |
| 50 | # %% |
| 51 | # 모델 |
| 52 | class Encoder(nn.Module): |
| 53 | """이미지 (배치, 1, 28, 28) → 잠재 변수 (배치, latent_size)""" |
| 54 | |
| 55 | def __init__(self, latent_size: int, k: int = 16): |
| 56 | super().__init__() |
| 57 | self.net = nn.Sequential( |
| 58 | nn.Conv2d(1, k, 3, stride=2), # 28 → 13 |
| 59 | nn.ReLU(), |
| 60 | nn.Conv2d(k, 2 * k, 3, stride=2), # 13 → 6 |
| 61 | nn.ReLU(), |
| 62 | nn.Conv2d(2 * k, 4 * k, 3, stride=1), # 6 → 4 |
| 63 | nn.ReLU(), |
| 64 | nn.Flatten(), |
| 65 | nn.Linear(4 * k * 4 * 4, latent_size), |
| 66 | nn.ReLU(), |
| 67 | ) |
| 68 | |
| 69 | def forward(self, x): |
| 70 | return self.net(x) |
| 71 | |
| 72 | |
| 73 | class Decoder(nn.Module): |
| 74 | """잠재 변수 (배치, latent_size) → 이미지 (배치, 1, 28, 28)""" |
| 75 | |
| 76 | def __init__(self, latent_size: int, k: int = 16): |
| 77 | super().__init__() |
| 78 | self.net = nn.Sequential( |
| 79 | nn.Linear(latent_size, 4 * k * 4 * 4), |
| 80 | nn.ReLU(), |
| 81 | nn.Unflatten(1, (4 * k, 4, 4)), |
| 82 | nn.ConvTranspose2d(4 * k, 2 * k, 3, stride=1), # 4 → 6 |
| 83 | nn.ReLU(), |
| 84 | nn.ConvTranspose2d(2 * k, k, 3, stride=2), # 6 → 13 |
| 85 | nn.ReLU(), |
| 86 | nn.ConvTranspose2d(k, 1, 3, stride=2, output_padding=1), # 13 → 28 |
| 87 | nn.Sigmoid(), |
| 88 | ) |
| 89 | |
| 90 | def forward(self, z): |
| 91 | return self.net(z) |
| 92 | |
| 93 | |
| 94 | class KMeans(nn.Module): |
| 95 | """군집 중심을 학습 가능한 파라미터로 둔 K-평균.""" |
| 96 | |
| 97 | def __init__(self, num_clusters: int, latent_size: int): |
| 98 | super().__init__() |
| 99 | self.centroids = nn.Parameter(torch.rand(num_clusters, latent_size)) |
| 100 | |
| 101 | def forward(self, z): |
| 102 | """각 잠재 변수의 군집 번호 (배치,)와 그 군집의 중심 (배치, latent_size)을 돌려준다.""" |
| 103 | # 가장 가까운 중심을 고르는 일(argmin)은 미분할 수 없으므로 기울기 없이 계산한다 |
| 104 | with torch.no_grad(): |
| 105 | assign = torch.cdist(z, self.centroids).argmin(dim=1) |
| 106 | return assign, self.centroids[assign] |
| 107 | |
| 108 | |
| 109 | # %% |
| 110 | # 학습 |
| 111 | def cluster_weight(epoch: int, t1: int, t2: int) -> float: |
| 112 | """에폭에 따른 군집 손실 가중치 alpha. |
| 113 | |
| 114 | 처음(t1까지)에는 아주 작게 두어 오토인코더가 먼저 자리를 잡게 하고, |
| 115 | t1~t2 구간에서 서서히 키운 뒤, t2부터는 LAMBDA로 고정한다. |
| 116 | """ |
| 117 | if epoch <= t1: |
| 118 | return LAMBDA / (t2 - t1) |
| 119 | if epoch < t2: |
| 120 | return LAMBDA * (epoch - t1) / (t2 - t1) |
| 121 | return LAMBDA |
| 122 | |
| 123 | |
| 124 | def compute_loss(encoder, decoder, kmeans, inputs, alpha: float) -> torch.Tensor: |
| 125 | """손실 = 복원 손실 + alpha * 군집 손실""" |
| 126 | latent = encoder(inputs) |
| 127 | outputs = decoder(latent) |
| 128 | _, centroids = kmeans(latent) |
| 129 | loss_rec = nn.functional.mse_loss(outputs, inputs) # 입력을 얼마나 잘 복원하는가 |
| 130 | loss_clt = nn.functional.mse_loss(latent, centroids) # 잠재 변수가 자기 군집 중심에 가까운가 |
| 131 | return loss_rec + alpha * loss_clt |
| 132 | |
| 133 | |
| 134 | def train_one_epoch(encoder, decoder, kmeans, optimizer, train_x, alpha: float) -> float: |
| 135 | """한 에폭을 돌고 평균 손실을 돌려준다.""" |
| 136 | encoder.train() |
| 137 | decoder.train() |
| 138 | running_loss, n_batches = 0.0, 0 |
| 139 | # 매 에폭 순서를 섞어 미니배치로 나눈다 |
| 140 | for idx in torch.randperm(len(train_x), device=train_x.device).split(BATCH_SIZE): |
| 141 | loss = compute_loss(encoder, decoder, kmeans, train_x[idx], alpha) |
| 142 | optimizer.zero_grad() |
| 143 | loss.backward() |
| 144 | optimizer.step() |
| 145 | running_loss += loss.item() |
| 146 | n_batches += 1 |
| 147 | return running_loss / n_batches |
| 148 | |
| 149 | |
| 150 | # %% |
| 151 | # 평가 |
| 152 | @torch.inference_mode() |
| 153 | def predict(encoder, kmeans, x: torch.Tensor): |
| 154 | """(잠재 변수, 군집 번호)를 넘파이 배열로 돌려준다.""" |
| 155 | encoder.eval() |
| 156 | latents, assigns = [], [] |
| 157 | for batch in x.split(1000): |
| 158 | z = encoder(batch) |
| 159 | assign, _ = kmeans(z) |
| 160 | latents.append(z.cpu()) |
| 161 | assigns.append(assign.cpu()) |
| 162 | return torch.cat(latents).numpy(), torch.cat(assigns).numpy() |
| 163 | |
| 164 | |
| 165 | def cluster_acc(y_true: np.ndarray, y_pred: np.ndarray) -> float: |
| 166 | """군집 정확도. 군집 번호는 실제 라벨과 순서가 다르므로 가장 잘 맞는 짝을 찾아 계산한다.""" |
| 167 | d = max(y_pred.max(), y_true.max()) + 1 |
| 168 | w = np.zeros((d, d), dtype=np.int64) # w[i, j]: 군집 i에 속한 라벨 j의 개수 |
| 169 | np.add.at(w, (y_pred, y_true), 1) |
| 170 | # 헝가리안 알고리즘: 맞는 개수의 합이 최대가 되도록 군집과 라벨을 일대일로 짝짓는다 |
| 171 | rows, cols = linear_sum_assignment(w, maximize=True) |
| 172 | return float(w[rows, cols].sum() / y_pred.size) |
| 173 | |
| 174 | |
| 175 | # %% |
| 176 | # 가중치 저장과 불러오기 |
| 177 | def save_checkpoint(encoder, decoder, kmeans) -> None: |
| 178 | MODEL_DIR.mkdir(parents=True, exist_ok=True) |
| 179 | state = { |
| 180 | "encoder": encoder.state_dict(), |
| 181 | "decoder": decoder.state_dict(), |
| 182 | "kmeans": kmeans.state_dict(), |
| 183 | } |
| 184 | torch.save(state, CKPT_PATH) |
| 185 | |
| 186 | |
| 187 | def load_checkpoint(encoder, decoder, kmeans, device: torch.device) -> None: |
| 188 | state = torch.load(CKPT_PATH, map_location=device, weights_only=True) |
| 189 | encoder.load_state_dict(state["encoder"]) |
| 190 | decoder.load_state_dict(state["decoder"]) |
| 191 | kmeans.load_state_dict(state["kmeans"]) |
| 192 | |
| 193 | |
| 194 | # %% |
| 195 | # 그림 |
| 196 | @torch.inference_mode() |
| 197 | def plot_reconstruction(encoder, decoder, samples: torch.Tensor) -> None: |
| 198 | """원본(위)과 복원 이미지(아래)를 나란히 그린다.""" |
| 199 | encoder.eval() |
| 200 | decoder.eval() |
| 201 | recon = decoder(encoder(samples)) |
| 202 | n = len(samples) |
| 203 | fig, axes = plt.subplots(2, n, figsize=(n, 2.3)) |
| 204 | for i in range(n): |
| 205 | axes[0, i].imshow(samples[i, 0].cpu().numpy(), cmap="gray") |
| 206 | axes[1, i].imshow(recon[i, 0].cpu().numpy(), cmap="gray") |
| 207 | axes[0, i].axis("off") |
| 208 | axes[1, i].axis("off") |
| 209 | fig.suptitle("top: input / bottom: reconstruction") |
| 210 | save_fig("ch08", "08_deep_kmeans_reconstruction") |
| 211 | |
| 212 | |
| 213 | def plot_tsne(latents: np.ndarray, y_true: np.ndarray, y_pred: np.ndarray) -> None: |
| 214 | """잠재 변수를 t-SNE(10.2절)로 2차원에 펼쳐, 실제 숫자(왼쪽)와 군집(오른쪽)으로 색칠한다.""" |
| 215 | embedded = TSNE(n_components=2, random_state=0).fit_transform(latents) |
| 216 | _, axes = plt.subplots(1, 2, figsize=(14, 6.5)) |
| 217 | for ax, colors, title in [(axes[0], y_true, "true digit"), (axes[1], y_pred, "cluster")]: |
| 218 | for c in range(NUM_CLUSTERS): |
| 219 | mask = colors == c |
| 220 | ax.scatter(embedded[mask, 0], embedded[mask, 1], s=6, color=f"C{c}", label=str(c)) |
| 221 | ax.set_title(title) |
| 222 | ax.legend(markerscale=3, fontsize=8) |
| 223 | save_fig("ch08", "08_deep_kmeans_tsne") |