TelegramOpen channel
Sofiia N
Merged · Machine Learning

Алгоритми кластеризації

Розберемо, що таке задачі кластеризації як підхід навчання без учителя та де вони застосовуються в реальних бізнес-сценаріях. З нуля реалізуємо алгоритм KMeans, а також використаємо sklearn для побудови інших алгоритмів кластеризації й проаналізуємо, які методи доцільно застосовувати для різних типів даних.

Code and results

Published version after Merge. Results were saved by the author; code does not run on this page.

Python · 1
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
Python · 2
def euclidean_distance(x, c):
  return np.sqrt(np.sum((x - c) ** 2))
Python · 3
def initialize_centroids(X, k):
    centroid_idx = np.random.choice(len(X), k, replace=False)
    centroid = X[centroid_idx]
    return centroid
Python · 4
def assign_clusters(X, k, c):
  clusters = {i: [] for i in range(k)}

  for x in X:
    distance = []
    for i in c:
      distance.append(euclidean_distance(x, i))
    min_idx = np.argmin(distance)
    clusters[min_idx].append(x)

  return clusters
Python · 5
def update_centroid(clusters):
  new_centroids = []
  for i in clusters:
    centroid = np.mean(clusters[i], axis=0)
    new_centroids.append(centroid)

  return np.array(new_centroids)
Python · 6
def kmeans(X, k, max_iter=100):
  centroid = initialize_centroids(X, k)
  clusters = assign_clusters(X, k, centroid)

  for i in range(max_iter):
    old_centroids = centroid.copy()
    new_centroids = update_centroid(clusters)

    if np.allclose(new_centroids, old_centroids):
      centroid = new_centroids
      break

    centroid = new_centroids
    clusters = assign_clusters(X, k, centroid)

  return clusters, centroid
Python · 7
X, y = make_blobs(n_samples=300, n_features=2, random_state=42)
Python · 8
clusters, centroid = kmeans(X, 3, 100)
Python · 9
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.scatter(centroid[:, 0], centroid[:, 1],
            color='red', marker='X', s=200,
            label='Centroids')

plt.legend()
plt.grid()
plt.show()
Results saved by the author in ColabCell 9 output
Python · 10

Community reviews