Last active
February 18, 2016 16:00
-
-
Save tpudlik/c2bdbbb19e8af17d8041 to your computer and use it in GitHub Desktop.
Reproduces the spectral clustering example of Figure 14.29 in Hastie, Tibshirani and Friedman (2nd ed).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Reproduce the spectral clustering example of Figure 14.29. | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from sklearn.cluster import SpectralClustering | |
def sample(n): | |
assert n % 3 == 0 | |
angles = np.random.uniform(0, 2*np.pi, size=(n,1)) | |
radii = np.vstack((np.ones((n/3,1)), 2.8*np.ones((n/3,1)), 5*np.ones((n/3,1)))) | |
x = radii*np.cos(angles) + np.random.normal(scale=0.25, size=(n,1)) | |
y = radii*np.sin(angles) + np.random.normal(scale=0.25, size=(n,1)) | |
return np.hstack((x, y)) | |
if __name__ == "__main__": | |
data = sample(450) | |
clusters = 3 | |
sc = SpectralClustering(n_clusters=clusters, n_neighbors=10, | |
affinity="nearest_neighbors") | |
labels = sc.fit_predict(data) | |
pts = [] | |
for c in xrange(clusters): | |
selector = (labels == c) | |
pts.append(data[selector, :]) | |
for c in xrange(clusters): | |
plt.plot(pts[c][:,0], pts[c][:,1], 'o') | |
plt.axes().set_aspect("equal") | |
plt.tight_layout() | |
plt.show() |
Author
tpudlik
commented
Feb 18, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment