Example of k-means algorithm implemented by python (k-means clustering algorithm)

Source: Internet
Author: User
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 ()

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.