Skip to content

Instantly share code, notes, and snippets.

@jizongFox
Created June 24, 2021 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jizongFox/ef4fb0277a79fa2056c8933fe494526b to your computer and use it in GitHub Desktop.
Save jizongFox/ef4fb0277a79fa2056c8933fe494526b to your computer and use it in GitHub Desktop.
k-Center-Greedy algorithm
# demo for https://arxiv.org/pdf/1708.00489.pdf and Fig. 3 of https://arxiv.org/pdf/2106.08265.pdf
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
sample_num = 1000
x_sample = np.random.uniform(-1, 1, sample_num)
y_sample = np.random.uniform(-1, 1, sample_num)
dataset = np.stack([x_sample, y_sample], axis=1)
percent = 0.1
def k_greed(dataset, percentage: float):
s = [dataset[0]]
remain_data = [x for x in dataset[1:]]
d_func = lambda x, y: ((x - y) ** 2).sum()
indicator = tqdm()
with indicator:
while True:
max_index = None
max_distance = 0
for i, data in enumerate(remain_data):
distance = min([d_func(data, _s) for _s in s])
if distance > max_distance:
max_distance = distance
max_index = i
s.append(remain_data[max_index])
del remain_data[i]
indicator.update()
if float(len(s) / len(dataset)) > percentage:
return np.stack(s, axis=0)
plt.figure(0)
m_set = k_greed(dataset, percent)
plt.scatter(dataset[:, 0], dataset[:, 1])
plt.scatter(m_set[:, 0], m_set[:, 1], color="r")
plt.figure(1)
r_set = dataset[np.random.permutation(range(len(dataset)))[: int(len(dataset) * percent)]]
plt.scatter(dataset[:, 0], dataset[:, 1])
plt.scatter(r_set[:, 0], r_set[:, 1], color="r")
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment