Advertisement
Guest User

Untitled

a guest
Jan 19th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.75 KB | None | 0 0
  1. from sklearn.metrics import silhouette_samples, silhouette_score
  2. from sklearn.cluster import KMeans
  3.  
  4. import matplotlib.cm as cm
  5.  
  6. range_n_clusters = [2, 3, 4, 5, 6, 7, 8, 9, 10]
  7.  
  8. score = pd.Series()
  9. features = [
  10. 'angle(X,gravityMean)',
  11. 'tGravityAccMag-std()'
  12. ]
  13.  
  14. for n_cluster in range_n_clusters:
  15. # Create a subplot with 1 row and 2 columns
  16. fig, (ax1, ax2) = plt.subplots(1, 2)
  17. fig.set_size_inches(18, 7)
  18.  
  19. # The 1st subplot is the silhouette plot
  20. # The silhouette coefficient can range from -1, 1 but in this example all
  21. # lie within [-0.1, 1]
  22. ax1.set_xlim([-0.2, 1])
  23. # The (n_clusters+1)*10 is for inserting blank space between silhouette
  24. # plots of individual clusters, to demarcate them clearly.
  25. ax1.set_ylim([0, len(dane) + (n_cluster + 1) * 10])
  26.  
  27. kmeans = KMeans(n_clusters=n_cluster, random_state=0).fit(X_test)
  28. score = score.append(pd.Series(kmeans.inertia_))
  29. cluster_labels = kmeans.fit_predict(dane[features])
  30.  
  31. silhouette_avg = silhouette_score(dane[features], cluster_labels)
  32.  
  33. # Compute the silhouette scores for each sample
  34. sample_silhouette_values = silhouette_samples(dane[features], cluster_labels)
  35.  
  36. y_lower = 10
  37. for i in range(n_cluster):
  38. # Zebranie wyników sylwetek do próbek należących do klastra i ich sortowanie
  39. ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]
  40.  
  41. ith_cluster_silhouette_values.sort()
  42.  
  43. size_cluster_i = ith_cluster_silhouette_values.shape[0]
  44. y_upper = y_lower + size_cluster_i
  45.  
  46. color = cm.spectral(float(i) / n_cluster)
  47. ax1.fill_betweenx(np.arange(y_lower, y_upper),
  48. 0, ith_cluster_silhouette_values,
  49. facecolor=color, edgecolor=color, alpha=0.7)
  50.  
  51. # Etykieta sylwetek z numerami klastrów w środku
  52. ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
  53.  
  54. # Wyliczenie przesunięcia w pionie dla kolejnego wykresu
  55. y_lower = y_upper + 10 # 10 dla kolejnej próbki
  56.  
  57. ax1.set_title("Wykres sylwetek dla poszczegolnych klastrow.")
  58. ax1.set_xlabel("Wartosc sylwetek")
  59. ax1.set_ylabel("Etykiety klastrow")
  60.  
  61. # Wyrysowanie wartości średniej sylwetki
  62. ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
  63.  
  64. ax1.set_yticks([]) # Wyczyszczenie etykiety osi Y
  65. ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
  66.  
  67. # Drugi wykres będzie przedstawiał klastry
  68. colors = cm.spectral(cluster_labels.astype(float) / n_cluster)
  69. ax2.scatter(dane[features[0]], dane[features[1]], marker='.', s=30, lw=0, alpha=0.7,
  70. c=colors)
  71.  
  72. # Etykietowanie klastrów
  73. centers = kmeans.cluster_centers_
  74. # Rysowanie białych kółek w cetroidach
  75. ax2.scatter(centers[:, 0], centers[:, 1],
  76. marker='o', c="white", alpha=1, s=200)
  77.  
  78. # Numerowanie centroidów
  79. for i, c in enumerate(centers):
  80. ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1, s=50)
  81.  
  82. ax2.set_title("Wizualizacja grupowania danych.")
  83. ax2.set_xlabel("Wartosc pierwszej cechy")
  84. ax2.set_ylabel("Wartosc drugiej cechy")
  85.  
  86. plt.suptitle(("Analiza sylwetki dla algorytmu K-Srednich "
  87. "dla %d klastrow" % n_cluster),
  88. fontsize=14, fontweight='bold')
  89. plt.figtext(0.14, 0,
  90. ("Dla n_klastrow = ", n_cluster,
  91. "Srednia wartosc sylwetki jest: ", silhouette_avg,
  92. "Suma odleglosci od centroidow: ", kmeans.inertia_), fontsize=14)
  93. plt.show()
  94.  
  95.  
  96. plt.plot(range_n_clusters, score,'bo-')
  97. plt.title("Wykres lokciowy", fontsize=14, fontweight='bold')
  98. plt.xlabel("Ilosc klastrow")
  99. plt.ylabel("Suma odleglosci od centroidow")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement