DM2
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_blobs
x, y = make_blobs(n_samples=100, centers=3, n_features=2)
plt.scatter(x[:, 0], x[:, 1], c=y, cmap='gist_rainbow')
plt.show()
k = 3
center = 10*np.random.rand(k, 2)
dist_matrix = np.zeros((100, 3))
for i in range(k):
dist_matrix[:, i] = np.sum((x-center[i, :])**2, axis=1)
cluster_labels = np.argmin(dist_matrix, axis=1)
plt.scatter(x[:, 0], x[:, 1], c=cluster_labels, cmap='gist_rainbow')
plt.show()
for i in range(k):
center[i, :] = np.mean(x[cluster_labels == i, :], axis=0)
dist_matrix = np.zeros((100, 3))
for i in range(k):
dist_matrix[:, i] = np.sum((x-center[i, :])**2, axis=1)
cluster_labels = np.argmin(dist_matrix, axis=1)
plt.scatter(x[:, 0], x[:, 1], c=cluster_labels, cmap='gist_rainbow')
plt.show()