NUMPY—Kmeans聚类)
此代码实现了欧式距离聚类,k值在1-5之间
import numpy as np
import matplotlib. pyplot as plt
def show ( x, y, crowd) :
lable = [ ]
ans= 999999
flag= 0
for i in range ( len ( x) ) :
for j in range ( len ( crowd) ) :
d= np. sqrt( ( x[ i] - crowd[ j] [ 0 ] ) ** 2 + ( y[ i] - crowd[ j] [ 1 ] ) ** 2 )
if ans> d:
ans= d
flag = j
lable. append( flag)
ans= 999999
flag = 0
xx = [ ]
yy = [ ]
color = [ 'b' , 'c' , 'g' , 'k' , 'm' , 'r' , 'w' ]
flaglabel= [ ]
for i in range ( len ( crowd) ) :
xx. append( 0 )
yy. append( 0 )
flaglabel. append( 0 )
for i in range ( len ( x) ) :
plt. scatter( x[ i] , y[ i] , c= color[ lable[ i] ] )
xx[ lable[ i] ] += x[ i]
yy[ lable[ i] ] += y[ i]
flaglabel[ lable[ i] ] += 1
plt. pause( 1.5 )
plt. clf( )
for i in range ( len ( crowd) ) :
xx[ i] = xx[ i] / flaglabel[ i]
yy[ i] = yy[ i] / flaglabel[ i]
crowd[ i] [ 0 ] = xx[ i]
crowd[ i] [ 1 ] = yy[ i]
return crowd
if __name__ == '__main__' :
x = np. random. randn( 100 )
y = np. random. randn( 100 )
crowd = [ ]
k = int ( input ( "请输入k: " ) )
for i in range ( k) :
crowd. append( np. random. uniform( - 3 , 3 , 2 ) )
for _ in range ( k* 5 ) :
crowd = show( x, y, crowd)