1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
| import matplotlib.pyplot as plt import pandas as pd from sklearn.cluster import KMeans from sklearn.datasets import make_blobs
class LTKmeans: """ test_case_01流程: 1. 產生樣本資料: generate_test_data_set() 2. 繪製樣本資料: plot_data_set() 3. 計算SSE(sum of the squared errors,誤差平方和): calculate_sse() 4. 繪製SSE: plot_sse() 5. 計算與繪製分群結果: plot_foreach_kmeans_cluster() 6. 顯示圖形: show()
""" SAMPLE_SIZE = 0 SAMPLE_FEATURES = 0 SAMPLE_CLUSTER_NUM = 0 K_MAX = 0 SUBPLOT_COL = 4 SUBPLOT_ROW = 0 figsize = [16, 16]
data_set = None data_tags = None sse = [] figure = None
def __init__(self, title="K-means", sample_size=1000, sample_features=20, cluster_num=5, ): self.config(sample_size=sample_size, sample_features=sample_features, cluster_num=cluster_num, print_config=False, ) self._init_figure(title=title)
def in_notebook(self): try: from IPython import get_ipython if 'IPKernelApp' not in get_ipython().config: return False except ImportError: return False except AttributeError: return False return True
def _init_figure(self, title): plt.rcParams["figure.figsize"] = self.figsize plt.rcParams["figure.autolayout"] = True if not self.in_notebook(): plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] self.figure = plt.figure() self.figure.canvas.manager.set_window_title(title)
def config(self, sample_size=1000, sample_features=20, cluster_num=5, print_config=False, ): self.SAMPLE_CLUSTER_NUM = cluster_num self.K_MAX = self.SAMPLE_CLUSTER_NUM + 3 self.SAMPLE_SIZE = sample_size self.SAMPLE_FEATURES = sample_features self.SUBPLOT_ROW = int(self.K_MAX / self.SUBPLOT_COL) + 2
if print_config: print(f""" Config: 樣本數: {self.SAMPLE_SIZE} 樣本特徵數(維度): {self.SAMPLE_FEATURES} 聚類數: {self.SAMPLE_CLUSTER_NUM} """)
def generate_test_data_set(self): self.data_set, self.data_tags = make_blobs(n_samples=self.SAMPLE_SIZE, n_features=self.SAMPLE_FEATURES, centers=self.SAMPLE_CLUSTER_NUM, )
def plot_data_set(self): ax = self.figure.add_subplot(self.SUBPLOT_ROW, self.SUBPLOT_COL, 3, )
ax.set_title(f'Sample data appearance({self.SAMPLE_CLUSTER_NUM} groups)') ax.scatter(self.data_set.T[0], self.data_set.T[1], s=4, c=self.data_tags, cmap=plt.cm.Set1, )
ax = self.figure.add_subplot(self.SUBPLOT_ROW, self.SUBPLOT_COL, 4) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) ax.text(0.02, 0.9, f'Sample data size: {self.SAMPLE_SIZE}\nSample features(dimension): {self.SAMPLE_FEATURES}\nSample group size: {self.SAMPLE_CLUSTER_NUM}', ha='left', va='top', transform=ax.transAxes, fontsize=12)
def calculate_sse(self): self.sse.clear() for k in range(1, self.K_MAX + 1): kmeans = KMeans( n_clusters=k, n_init=100 ) kmeans.fit(self.data_set) self.sse.append(kmeans.inertia_)
def plot_sse(self): pd_sse = pd.Series(self.sse)
ax = self.figure.add_subplot(self.SUBPLOT_ROW, self.SUBPLOT_COL, (1, 2))
ax.plot(range(1, self.K_MAX + 1), pd_sse.tolist(), color='blue', marker='o', linewidth=1, markersize=4) ax.set_title('Elbow Method') ax.set_xlabel('K (number of clusters)')
def plot_foreach_kmeans_cluster(self): for k in range(1, self.K_MAX + 1): kmeans = KMeans(n_clusters=k, n_init=10) kmeans.fit(self.data_set) new_dy = kmeans.predict(self.data_set)
ax = self.figure.add_subplot(self.SUBPLOT_ROW, self.SUBPLOT_COL, k + 4) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) ax.set_title(f'{k} groups') ax.scatter(self.data_set.T[0], self.data_set.T[1], s=4, c=new_dy, cmap=plt.cm.Set1)
def show(self): if self.in_notebook(): plt.draw() else:
plt.show()
def run_test_case_01(self, sample_size, sample_features, cluster_num): self.config(sample_size, sample_features, cluster_num) self.generate_test_data_set() self.plot_data_set() self.calculate_sse() self.plot_sse() self.plot_foreach_kmeans_cluster() self.show()
test_case_configs = ( {'sample_size': 100, 'sample_features': 2, 'cluster_num': 6}, {'sample_size': 100, 'sample_features': 10, 'cluster_num': 6}, {'sample_size': 100, 'sample_features': 100, 'cluster_num': 6},
{'sample_size': 1000, 'sample_features': 2, 'cluster_num': 6}, {'sample_size': 1000, 'sample_features': 10, 'cluster_num': 6}, {'sample_size': 1000, 'sample_features': 100, 'cluster_num': 6},
{'sample_size': 10000, 'sample_features': 2, 'cluster_num': 6}, {'sample_size': 10000, 'sample_features': 10, 'cluster_num': 6}, {'sample_size': 10000, 'sample_features': 100, 'cluster_num': 6},
{'sample_size': 100, 'sample_features': 2, 'cluster_num': 12}, {'sample_size': 100, 'sample_features': 10, 'cluster_num': 12}, {'sample_size': 100, 'sample_features': 100, 'cluster_num': 12},
{'sample_size': 1000, 'sample_features': 2, 'cluster_num': 12}, {'sample_size': 1000, 'sample_features': 10, 'cluster_num': 12}, {'sample_size': 1000, 'sample_features': 100, 'cluster_num': 12},
{'sample_size': 10000, 'sample_features': 2, 'cluster_num': 12}, {'sample_size': 10000, 'sample_features': 10, 'cluster_num': 12}, {'sample_size': 10000, 'sample_features': 100, 'cluster_num': 12},
)
for config in test_case_configs: LTKmeans().run_test_case_01(**config)
|