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
| import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris from PCA import PCA
class K_Means(object): def __init__(self, n_clusters, max_iter=200, n_init=5): self.n_cluster = n_clusters self.max_iter = max_iter self.n_init = n_init
self.data = None self.dim = None self.n = None self.center_point = None self.data_label = None self.init_point = None
def rand_points(self): counter = 0 index = []
center_point = np.zeros((self.n_cluster, self.dim), dtype=np.float32) self.init_point = np.zeros((self.n_cluster, self.dim), dtype=np.float32) while counter < self.n_cluster: i = np.random.randint(0, self.n) if i not in index: index.append(i) center_point[counter] = self.data[i] counter += 1
self.init_point[:] = center_point[:]
def _k_means(self): self.rand_points() sign = np.zeros(self.n_cluster, dtype=np.bool) data_label = np.zeros((self.n, 1), dtype=np.float32) counter = 0 new_center_point = np.zeros_like(self.init_point) new_center_point[:] = self.init_point[:]
while True and counter < self.max_iter: for i in range(self.n): d = 1e+10 label = 0 for j in range(self.n_cluster): distance = np.linalg.norm(self.data[i] - new_center_point[j]) if distance < d: d = distance label = j data_label[i] = label
for i in range(self.n_cluster): cluster = np.argwhere(data_label == i)[:, 0] coord = self.data[cluster].T ave = [] for j in coord: ave.append(np.mean(j)) ave = np.array(ave)
if np.linalg.norm(new_center_point[i] - ave) > 1e-06:
sign[i] = False new_center_point[i] = ave else: sign[i] = True
if sign.all() == True: break
counter += 1 distance = 0 for j in range(self.n_cluster): data_labeld = self.data[np.argwhere(data_label == j)] for i in data_labeld: distance += np.linalg.norm(new_center_point[j] - i)
return new_center_point, data_label, distance / self.n
def fit(self, data): self.data = data self.dim = data.shape[1] self.n = data.shape[0] distance = 1e+10 init_point = np.zeros((self.n_cluster, self.dim), dtype=self.data.dtype) for _ in range(self.n_init): new_center_point, data_label, d = self._k_means()
if d < distance: distance = d self.center_point = new_center_point self.data_label = data_label init_point[:] = self.init_point[:]
self.init_point = init_point print('\n', 20 * '_', "K-Means 数据聚类", 20 * '_','\n') print('\n', 20 * '_', " 初始中心点 ", 20 * '_','\n', init_point) print('\n', 20 * '_', " 最终中心点 ", 20 * '_','\n', self.center_point)
print('\n', 20 * '_', ' 运行次数:{}'.format(self.n_init), 20 * '_')
def label_(self): return self.data_label.reshape(self.n)
def cluster_centers(self): return self.center_point
def predict(self, data): data = np.array(data) try: n, d = data.shape except ValueError: print("wrong data type") return False
if d != self.dim: print("wrong data type") return False
result = [] for i in range(len(data)): d = 1e+10 label = 0 for j in range(self.n_cluster): distance = np.linalg.norm(data[i] - self.center_point[j]) if distance < d: d = distance label = j result.append(label) return np.array(result)
class DataProduce: def __init__(self): pass
def test_data(self): data1 = np.random.multivariate_normal([10, 0], [[5, 0], [0, 5]], size=100) data2 = np.random.multivariate_normal([0, -10], [[5, 0], [0, 5]], size=100) data3 = np.random.multivariate_normal([0, 15], [[5, 0], [0, 5]], size=100) data4 = np.random.multivariate_normal([-10, 5],[[5, 0], [0, 5]], size=100)
target = [0 for _ in data1] target.extend([1 for _ in data2]) target.extend([2 for _ in data3]) target.extend([3 for _ in data4])
data = np.concatenate((data1,data2,data3,data4)) data_dict = {'data': data, 'target': target} return data_dict
def iris(self): return load_iris()
class Draw: def __init__(self): pass
def _2d_draw(self,d): data = d['data'] d_label = d['target'] cluster_num = len(set(d_label)) h = .1 x_min, x_max = data[:, 0].min() - 1, data[:, 0].max() + 1 y_min, y_max = data[:, 1].min() - 1, data[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) kmeans = K_Means(cluster_num) kmeans.fit(data) centroids = kmeans.cluster_centers()
label_pred = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])
z = label_pred.reshape(xx.shape) fig = plt.figure(figsize=(10, 5)) ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) ax1.set_title("initial data-set", size=20) ax2.set_title('K-means clustering ', size=20) ax2.imshow(z, interpolation='nearest', extent=(xx.min(), xx.max(), yy.min(), yy.max()), cmap=plt.cm.Paired, aspect='auto', origin='lower') ax2.plot(data[:, 0], data[:, 1], 'k.', markersize=2) ax1.scatter(*zip(*data), c=d_label, s=2)
ax2.scatter(*zip(*data), c='black', s=2) ax2.scatter(*zip(*centroids), c='w', marker='x', s=1000) ax2.scatter(*zip(*kmeans.init_point), c='r', marker='1', s=1000) plt.show()
if __name__ == '__main__': data = DataProduce()
test_data = data.test_data() iris = data.iris()
kmeans = K_Means(4)
kmeans.fit(iris['data']) pca = PCA(iris['data']) reduced_data = {'data': pca.pca(2), 'target': iris['target']}
draw = Draw() draw._2d_draw(reduced_data) draw._2d_draw(test_data)
|