python实现k均值算法示例(k均值聚类算法)

简单实现平面的点k均值分析,使用欧几里得距离,并用pylab展示。

代码如下:

import pylab as pl

#calc euclid squiredef calc_e_squire(a, b): return (a[0]- b[0]) ** 2 + (a[1] – b[1]) **2

#init the 20 pointa = [2,4,3,6,7,8,2,3,5,6,12,10,15,16,11,10,19,17,16,13]b = [5,6,1,4,2,4,3,1,7,9,16,11,19,12,15,14,11,14,11,19]

#define two k_valuek1 = [6,3]k2 = [6,1]

#defint tow clustersse_k1 = []sse_k2 = []while true: sse_k1 = [] sse_k2 = [] for i in range(20): e_squire1 = calc_e_squire(k1, [a[i], b[i]]) e_squire2 = calc_e_squire(k2, [a[i], b[i]]) if (e_squire1

发表评论