|
| 1 | +import numpy as np |
| 2 | +import torch |
| 3 | +from tqdm import tqdm |
| 4 | + |
| 5 | + |
| 6 | +def initialize(X, num_clusters): |
| 7 | + num_samples = len(X) |
| 8 | + indices = np.random.choice(num_samples, num_clusters, replace=False) |
| 9 | + initial_state = X[indices] |
| 10 | + return initial_state |
| 11 | + |
| 12 | + |
| 13 | +def kmeans( |
| 14 | + X, |
| 15 | + num_clusters, |
| 16 | + distance='euclidean', |
| 17 | + tol=1e-4, |
| 18 | + device=torch.device('cpu') |
| 19 | +): |
| 20 | + print(f'running k-means on {device}..') |
| 21 | + |
| 22 | + if distance == 'euclidean': |
| 23 | + pairwise_distance_function = pairwise_distance |
| 24 | + elif distance == 'cosine': |
| 25 | + pairwise_distance_function = pairwise_cosine |
| 26 | + else: |
| 27 | + raise NotImplementedError |
| 28 | + |
| 29 | + # convert to float |
| 30 | + X = X.float() |
| 31 | + |
| 32 | + # transfer to device |
| 33 | + X = X.to(device) |
| 34 | + |
| 35 | + # initialize |
| 36 | + initial_state = initialize(X, num_clusters) |
| 37 | + |
| 38 | + iteration = 0 |
| 39 | + tqdm_meter = tqdm(desc='[running kmeans]') |
| 40 | + while True: |
| 41 | + dis = pairwise_distance_function(X, initial_state) |
| 42 | + |
| 43 | + choice_cluster = torch.argmin(dis, dim=1) |
| 44 | + |
| 45 | + initial_state_pre = initial_state.clone() |
| 46 | + |
| 47 | + for index in range(num_clusters): |
| 48 | + selected = torch.nonzero(choice_cluster == index).squeeze().to(device) |
| 49 | + |
| 50 | + selected = torch.index_select(X, 0, selected) |
| 51 | + initial_state[index] = selected.mean(dim=0) |
| 52 | + |
| 53 | + center_shift = torch.sum( |
| 54 | + torch.sqrt( |
| 55 | + torch.sum((initial_state - initial_state_pre) ** 2, dim=1) |
| 56 | + )) |
| 57 | + |
| 58 | + # increment iteration |
| 59 | + iteration = iteration + 1 |
| 60 | + |
| 61 | + # update tqdm meter |
| 62 | + tqdm_meter.set_postfix( |
| 63 | + iteration=f'{iteration}', |
| 64 | + center_shift=f'{center_shift ** 2:0.6f}', |
| 65 | + tol=f'{tol:0.6f}' |
| 66 | + ) |
| 67 | + tqdm_meter.update() |
| 68 | + if center_shift ** 2 < tol: |
| 69 | + break |
| 70 | + |
| 71 | + return choice_cluster.cpu(), initial_state.cpu() |
| 72 | + |
| 73 | + |
| 74 | +def kmeans_predict( |
| 75 | + X, |
| 76 | + cluster_centers, |
| 77 | + distance='euclidean', |
| 78 | + device=torch.device('cpu') |
| 79 | +): |
| 80 | + print(f'predicting on {device}..') |
| 81 | + |
| 82 | + if distance == 'euclidean': |
| 83 | + pairwise_distance_function = pairwise_distance |
| 84 | + elif distance == 'cosine': |
| 85 | + pairwise_distance_function = pairwise_cosine |
| 86 | + else: |
| 87 | + raise NotImplementedError |
| 88 | + |
| 89 | + # convert to float |
| 90 | + X = X.float() |
| 91 | + |
| 92 | + # transfer to device |
| 93 | + X = X.to(device) |
| 94 | + |
| 95 | + dis = pairwise_distance_function(X, cluster_centers) |
| 96 | + choice_cluster = torch.argmin(dis, dim=1) |
| 97 | + |
| 98 | + return choice_cluster.cpu() |
| 99 | + |
| 100 | + |
| 101 | +def pairwise_distance(data1, data2, device=torch.device('cpu')): |
| 102 | + # transfer to device |
| 103 | + data1, data2 = data1.to(device), data2.to(device) |
| 104 | + |
| 105 | + # N*1*M |
| 106 | + A = data1.unsqueeze(dim=1) |
| 107 | + |
| 108 | + # 1*N*M |
| 109 | + B = data2.unsqueeze(dim=0) |
| 110 | + |
| 111 | + dis = (A - B) ** 2.0 |
| 112 | + # return N*N matrix for pairwise distance |
| 113 | + dis = dis.sum(dim=-1).squeeze() |
| 114 | + return dis |
| 115 | + |
| 116 | + |
| 117 | +def pairwise_cosine(data1, data2, device=torch.device('cpu')): |
| 118 | + # transfer to device |
| 119 | + data1, data2 = data1.to(device), data2.to(device) |
| 120 | + |
| 121 | + # N*1*M |
| 122 | + A = data1.unsqueeze(dim=1) |
| 123 | + |
| 124 | + # 1*N*M |
| 125 | + B = data2.unsqueeze(dim=0) |
| 126 | + |
| 127 | + # normalize the points | [0.3, 0.4] -> [0.3/sqrt(0.09 + 0.16), 0.4/sqrt(0.09 + 0.16)] = [0.3/0.5, 0.4/0.5] |
| 128 | + A_normalized = A / A.norm(dim=-1, keepdim=True) |
| 129 | + B_normalized = B / B.norm(dim=-1, keepdim=True) |
| 130 | + |
| 131 | + cosine = A_normalized * B_normalized |
| 132 | + |
| 133 | + # return N*N matrix for pairwise distance |
| 134 | + cosine_dis = 1 - cosine.sum(dim=-1).squeeze() |
| 135 | + return cosine_dis |
0 commit comments