Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from sklearn.cluster import OPTICS, cluster_optics_dbscan
- import matplotlib.gridspec as gridspec
- import matplotlib.pyplot as plt
- import numpy as np
- clust = OPTICS(min_samples=2, xi=.005, min_cluster_size=0.05)
- # Run the fit
- clust.fit(X)
- eps_1 = 2
- labels_050 = cluster_optics_dbscan(reachability=clust.reachability_,
- core_distances=clust.core_distances_,
- ordering=clust.ordering_, eps=eps_1)
- eps_2 = 0.1
- labels_200 = cluster_optics_dbscan(reachability=clust.reachability_,
- core_distances=clust.core_distances_,
- ordering=clust.ordering_, eps=eps_2)
- space = np.arange(len(X))
- reachability = clust.reachability_[clust.ordering_]
- labels = clust.labels_[clust.ordering_]
- plt.figure(figsize=(20, 14))
- G = gridspec.GridSpec(2, 3)
- ax1 = plt.subplot(G[0, :])
- ax2 = plt.subplot(G[1, 0])
- ax3 = plt.subplot(G[1, 1])
- ax4 = plt.subplot(G[1, 2])
- # Reachability plot
- colors = ['g.', 'r.', 'b.', 'y.', 'c.']
- for klass, color in zip(range(0, 5), colors):
- Xk = space[labels == klass]
- Rk = reachability[labels == klass]
- ax1.plot(Xk, Rk, color, alpha=0.3)
- ax1.plot(space[labels == -1], reachability[labels == -1], 'k.', alpha=0.3)
- ax1.plot(space, np.full_like(space, float(eps_1), dtype=float), 'k-', alpha=0.5)
- ax1.plot(space, np.full_like(space, float(eps_2), dtype=float), 'k-.', alpha=0.5)
- ax1.set_ylabel('Reachability (epsilon distance)')
- ax1.set_title('Reachability Plot')
- # OPTICS
- colors = ['g.', 'r.', 'b.', 'y.', 'c.']
- for klass, color in zip(range(0, 5), colors):
- Xk = X[clust.labels_ == klass]
- ax2.plot(Xk[:, 0], Xk[:, 1], color, alpha=0.3)
- ax2.plot(X[clust.labels_ == -1, 0], X[clust.labels_ == -1, 1], 'k+', alpha=0.1)
- n_clusters = len(set(clust.labels_)) - (1 if -1 in clust.labels_ else 0)
- ax2.set_title('cluster {} Automatic Clustering\nOPTICS xi'.format(n_clusters))
- # DBSCAN at 0.5
- colors = ['g', 'greenyellow', 'olive', 'r', 'b', 'c']
- for klass, color in zip(range(0, 6), colors):
- Xk = X[labels_050 == klass]
- ax3.plot(Xk[:, 0], Xk[:, 1], color, alpha=0.3, marker='.')
- ax3.plot(X[labels_050 == -1, 0], X[labels_050 == -1, 1], 'k+', alpha=0.1)
- n_clusters = len(set(labels_050)) - (1 if -1 in labels_050 else 0)
- ax3.set_title('cluster {} Clustering at {} epsilon cut\nDBSCAN'.format(n_clusters,eps_1))
- # DBSCAN at 2.
- colors = ['g.', 'm.', 'y.', 'c.']
- for klass, color in zip(range(0, 4), colors):
- Xk = X[labels_200 == klass]
- ax4.plot(Xk[:, 0], Xk[:, 1], color, alpha=0.3)
- ax4.plot(X[labels_200 == -1, 0], X[labels_200 == -1, 1], 'k+', alpha=0.1)
- n_clusters = len(set(labels_200)) - (1 if -1 in labels_200 else 0)
- ax4.set_title('cluster {} Clustering at {} epsilon cut\nDBSCAN'.format(n_clusters,eps_2))
- plt.savefig('f2')
- plt.tight_layout()
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement