# Source: content/notes/ml/unsupervised-learning.md
# Independent CPU example; use the curriculum environment.
# See /notes/ml/#example-environment or /notes/deep-learning/#example-environment.

import numpy as np
from sklearn.cluster import DBSCAN, HDBSCAN, KMeans, SpectralClustering
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score

X, truth = make_moons(n_samples=300, noise=0.045, random_state=33)
models = {
    "KMeans": KMeans(n_clusters=2, n_init=10, random_state=33),
    "DBSCAN": DBSCAN(eps=0.2, min_samples=5),
    "HDBSCAN": HDBSCAN(min_cluster_size=15, min_samples=5),
    "spectral": SpectralClustering(n_clusters=2, affinity="nearest_neighbors",
        n_neighbors=12, assign_labels="kmeans", random_state=33),
}
for name, model in models.items():
    labels = model.fit_predict(X)
    assert labels.shape == truth.shape
    print(name, "ARI", adjusted_rand_score(truth, labels),
          "noise fraction", np.mean(labels == -1))
W = np.array([[0., 1., 0., 0.], [1., 0., 0., 0.],
              [0., 0., 0., 1.], [0., 0., 1., 0.]])
L = np.diag(W.sum(axis=1)) - W
eigenvalues = np.linalg.eigvalsh(L)
assert np.count_nonzero(np.isclose(eigenvalues, 0)) == 2
print("Two-component Laplacian eigenvalues:", eigenvalues)
