|
| 1 | +import numpy as np |
| 2 | +import matplotlib.pyplot as plt |
| 3 | +import warnings |
| 4 | + |
| 5 | + |
| 6 | +def plot_kmeans_interactive(min_clusters=1, max_clusters=6): |
| 7 | + #from IPython.html.widgets import interact |
| 8 | + from ipywidgets import interact |
| 9 | + from sklearn.metrics.pairwise import euclidean_distances |
| 10 | + from sklearn.datasets.samples_generator import make_blobs |
| 11 | + |
| 12 | + with warnings.catch_warnings(): |
| 13 | + warnings.filterwarnings('ignore') |
| 14 | + |
| 15 | + X, y = make_blobs(n_samples=300, centers=4, |
| 16 | + random_state=0, cluster_std=0.60) |
| 17 | + |
| 18 | + def _kmeans_step(frame=0, n_clusters=4): |
| 19 | + rng = np.random.RandomState(2) |
| 20 | + labels = np.zeros(X.shape[0]) |
| 21 | + centers = rng.randn(n_clusters, 2) |
| 22 | + |
| 23 | + nsteps = frame // 3 |
| 24 | + |
| 25 | + for i in range(nsteps + 1): |
| 26 | + old_centers = centers |
| 27 | + if i < nsteps or frame % 3 > 0: |
| 28 | + dist = euclidean_distances(X, centers) |
| 29 | + labels = dist.argmin(1) |
| 30 | + |
| 31 | + if i < nsteps or frame % 3 > 1: |
| 32 | + centers = np.array([X[labels == j].mean(0) |
| 33 | + for j in range(n_clusters)]) |
| 34 | + nans = np.isnan(centers) |
| 35 | + centers[nans] = old_centers[nans] |
| 36 | + |
| 37 | + |
| 38 | + # plot the data and cluster centers |
| 39 | + plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='rainbow', |
| 40 | + vmin=0, vmax=n_clusters - 1); |
| 41 | + plt.scatter(old_centers[:, 0], old_centers[:, 1], marker='o', |
| 42 | + c=np.arange(n_clusters), |
| 43 | + s=200, cmap='rainbow') |
| 44 | + plt.scatter(old_centers[:, 0], old_centers[:, 1], marker='o', |
| 45 | + c='black', s=50) |
| 46 | + |
| 47 | + # plot new centers if third frame |
| 48 | + if frame % 3 == 2: |
| 49 | + for i in range(n_clusters): |
| 50 | + plt.annotate('', centers[i], old_centers[i], |
| 51 | + arrowprops=dict(arrowstyle='->', linewidth=1)) |
| 52 | + plt.scatter(centers[:, 0], centers[:, 1], marker='o', |
| 53 | + c=np.arange(n_clusters), |
| 54 | + s=200, cmap='rainbow') |
| 55 | + plt.scatter(centers[:, 0], centers[:, 1], marker='o', |
| 56 | + c='black', s=50) |
| 57 | + |
| 58 | + plt.xlim(-4, 4) |
| 59 | + plt.ylim(-2, 10) |
| 60 | + |
| 61 | + if frame % 3 == 1: |
| 62 | + plt.text(3.8, 9.5, "1. Reassign points to nearest centroid", |
| 63 | + ha='right', va='top', size=14) |
| 64 | + elif frame % 3 == 2: |
| 65 | + plt.text(3.8, 9.5, "2. Update centroids to cluster means", |
| 66 | + ha='right', va='top', size=14) |
| 67 | + |
| 68 | + |
| 69 | + return interact(_kmeans_step, frame=np.arange(0, 50), |
| 70 | + n_clusters=np.arange(min_clusters, max_clusters)) |
| 71 | + |
| 72 | + |
| 73 | +def plot_image_components(x, coefficients=None, mean=0, components=None, |
| 74 | + imshape=(8, 8), n_components=6, fontsize=12): |
| 75 | + if coefficients is None: |
| 76 | + coefficients = x |
| 77 | + |
| 78 | + if components is None: |
| 79 | + components = np.eye(len(coefficients), len(x)) |
| 80 | + |
| 81 | + mean = np.zeros_like(x) + mean |
| 82 | + |
| 83 | + |
| 84 | + fig = plt.figure(figsize=(1.2 * (5 + n_components), 1.2 * 2)) |
| 85 | + g = plt.GridSpec(2, 5 + n_components, hspace=0.3) |
| 86 | + |
| 87 | + def show(i, j, x, title=None): |
| 88 | + ax = fig.add_subplot(g[i, j], xticks=[], yticks=[]) |
| 89 | + ax.imshow(x.reshape(imshape), interpolation='nearest') |
| 90 | + if title: |
| 91 | + ax.set_title(title, fontsize=fontsize) |
| 92 | + |
| 93 | + show(slice(2), slice(2), x, "True") |
| 94 | + |
| 95 | + approx = mean.copy() |
| 96 | + show(0, 2, np.zeros_like(x) + mean, r'$\mu$') |
| 97 | + show(1, 2, approx, r'$1 \cdot \mu$') |
| 98 | + |
| 99 | + for i in range(0, n_components): |
| 100 | + approx = approx + coefficients[i] * components[i] |
| 101 | + show(0, i + 3, components[i], r'$c_{0}$'.format(i + 1)) |
| 102 | + show(1, i + 3, approx, |
| 103 | + r"${0:.2f} \cdot c_{1}$".format(coefficients[i], i + 1)) |
| 104 | + plt.gca().text(0, 1.05, '$+$', ha='right', va='bottom', |
| 105 | + transform=plt.gca().transAxes, fontsize=fontsize) |
| 106 | + |
| 107 | + show(slice(2), slice(-2, None), approx, "Approx") |
| 108 | + |
| 109 | + |
| 110 | +def plot_pca_interactive(data, n_components=6): |
| 111 | + from sklearn.decomposition import PCA |
| 112 | + #from IPython.html.widgets import interact |
| 113 | + from ipywidgets import interact |
| 114 | + |
| 115 | + pca = PCA(n_components=n_components) |
| 116 | + Xproj = pca.fit_transform(data) |
| 117 | + |
| 118 | + def show_decomp(i=0): |
| 119 | + plot_image_components(data[i], Xproj[i], |
| 120 | + pca.mean_, pca.components_) |
| 121 | + |
| 122 | + interact(show_decomp, i=(0, data.shape[0] - 1)); |
0 commit comments