image_output_1.png
from sklearn import cluster

from sklearn.preprocessing import StandardScaler

import matplotlib.pyplot as plt

import numpy as np

import time

import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn import cluster
from sklearn.neighbors import kneighbors_graph
from sklearn.preprocessing import StandardScaler
from pylab import rcParams
np.random.seed(0)
n_samples = 500
colors = np.array([x for x in 'bgrcmykbgrcmykbgrcmykbgrcmyk'])
colors = np.hstack([colors] * 20)

datasets = [[[0, 0]], [[0, 0]], [[0, 0]], [[0, 0]]]
mu = 0.3
centers = [[(0, 0.45), (0.9, 0.5), (0.45, 0.9), (0.45, 0)], [(0, 0.2), (0.8, 0), (0.2, 1), (1, 0.8)], [(0, 0), (0.9, 0.9), (0, 0.9), (0.9, 0)], [(0, 0), (0.9, 0), (0.45, 0.779), (0.45, 0.259)]]
for i, c in enumerate(centers):
    for x, y in c:
        num1 = np.random.normal(x, mu, n_samples)
        num2 = np.random.normal(y, mu, n_samples)
        nums = np.vstack((num1, num2)).T
        datasets[i] = np.vstack((datasets[i], nums))
datasets = list(zip(datasets, ['a', 'b', 'c', 'd']))
plot_num = 1
for (X, lbl), c in zip(datasets, centers):
    center_colors = colors[:len(centers)]
    plt.xlim(-1, 2)
    plt.ylim(-1, 2)
    plt.xticks(())
    plt.yticks(())
    plt.text(0.01, 0.01, lbl, transform=plt.gca().transAxes, size=15, horizontalalignment='left')
    plot_num += 1

plot_num = 1
for i_dataset, dataset in enumerate(datasets):
    X, lbl = dataset
    X = StandardScaler().fit_transform(X)
    two_means = cluster.MiniBatchKMeans(n_clusters=4)
    algorithm = two_means
    name = 'MiniBatchKMeans'
    t0 = time.time()
    algorithm.fit(X)
    t1 = time.time()
    if hasattr(algorithm, 'labels_'):
        y_pred = algorithm.labels_.astype(np.int)
    else:
        y_pred = algorithm.predict(X)
    plt.subplot(2, 2, plot_num)
    if i_dataset == 0:
        plt.title(name, size=18)
    plt.scatter(X[:, 0], X[:, 1], color=colors[y_pred].tolist(), s=10)
    if hasattr(algorithm, 'cluster_centers_'):
        centers = algorithm.cluster_centers_
        center_colors = colors[:len(centers)]
        plt.scatter(centers[:, 0], centers[:, 1], s=100, c=center_colors)
    plt.xlim(-2, 2)
    plt.ylim(-2, 2)
    plt.xticks(())
    plt.yticks(())
    plt.text(0.99, 0.01, ('%.2fs' % (t1 - t0)).lstrip('0'), transform=plt.gca().transAxes, size=15, horizontalalignment='right')
    plt.text(0.01, 0.01, lbl, transform=plt.gca().transAxes, size=15, horizontalalignment='left')
    plot_num += 1
plt.show()