Python implementation K-Mean algorithm example (K-means clustering algorithm) _python

Source: Internet
Author: User

Simple realization of the point k mean of the plane, using Euclidean distance, and Pylab display.

Copy Code code 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 Point
A = [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_value
K1 = [6,3]
K2 = [6,1]

#defint Tow Cluster
SSE_K1 = []
Sse_k2 = []
while True:
    sse_k1 = []
  & nbsp SSE_K2 = []
    for I in range:
        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] to 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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.