This article mainly introduces the example of implementing the k-means algorithm in python, simple implementation of point K-means analysis in the plane, using Euclidean distance, and using pylab, if you need it, you can refer to the simple implementation of point K mean analysis in the plane, use Euclidean distance, and use pylab to display it.
The code is as follows:
Import pylab as pl
# Calc Euclid squire
Def calc_e_squire (a, B ):
Return (a [0]-B [0]) ** 2 + (a [1]-B [1]) ** 2
# Init the 20 point
A = [,]
B = [,]
# Define two k_value
K1 = [6, 3]
K2 = [6, 1]
# Defint tow cluster
Sse_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 <= e_squire2 ):
Sse_k1.append (I)
Else:
Sse_k2.append (I)
# Change k_value
K1_x = sum ([a [I] for I in sse_k1])/len (sse_k1)
K1_y = sum ([B [I] for I in sse_k1])/len (sse_k1)
K2_x = sum ([a [I] for I in sse_k2])/len (sse_k2)
K2_y = sum ([B [I] for I in sse_k2])/len (sse_k2)
If k1! = [K1_x, k1_y] or k2! = [K2_x, k2_y]:
K1 = [k1_x, k1_y]
K2 = [k2_x, k2_y]
Else:
Break
Kv1_x = [a [I] for I in sse_k1]
Kv1_y = [B [I] for I in sse_k1]
Kv2_x = [a [I] for I in sse_k2]
Kv2_y = [B [I] for I in sse_k2]
Pl. plot (kv1_x, kv1_y, 'o ')
Pl. plot (kv2_x, kv2_y, 'or ')
Pl. xlim (1, 20)
Pl. ylim (1, 20)
Pl. show ()