其他分享
首页 > 其他分享> > Kmeans_鸢尾花聚类

Kmeans_鸢尾花聚类

作者:互联网

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
def distance(vex1,vex2):
    return np.sqrt(np.sum(np.power(vex1-vex2,2)))
def kMeans_way(S,k,distMeas=distance):
    m=np.shape(S)[0]
    
    sampleTag = np.zeros(m)
    n=np.shape(S)[1]
    print (m,n)
    clusterCenter = np.mat(np.zeros((k,n)))
    for j in range(n):
        minJ=min(S[:,j])
        maxJ=max(S[:,j])
        rangeJ=float(maxJ-minJ)
        clusterCenter[:,j]=np.mat(minJ + rangeJ*np.random.rand(k,1))
    #print (clusterCenter)
    
    sampleTagChanged = True
    SSE = 0.0
    while sampleTagChanged:
        sampleTagChanged = False
        SSE = 0.0
        for i in range(m):
            minD = np.inf
            minIndex = -1
            for j in range(k):
                d=distMeas(clusterCenter[j,:],S[i,:])
                if d<minD:
                    minD=d
                    minIndex=j
            if sampleTag[i]!=minIndex:
                sampleTagChanged = True
            sampleTag[i] = minIndex
            SSE+=minD**2
        print (SSE)
        for i in range(k):

            ClustI=S[np.nonzero(sampleTag[:]==i)[0]]
            clusterCenter[i,:]= np.mean(ClustI,axis=0)
            
    return clusterCenter,sampleTag,SSE         
def draw_pic(samples,sampleTag,clusterCenter):
    k=len(clusterCenter)
    plt.rcParams['font.sans-serif']=['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    markers=['sg','py','ob','pr']
   
    for i in range(k):
        data_pos = samples[sampleTag== i]
        plt.plot(data_pos[:,0].tolist(),data_pos[:,1].tolist(),markers[i])

    plt.plot(clusterCenter[:,0].tolist(),clusterCenter[:,1].tolist(),"r*",markersize=20)

    plt.title('鸢尾花')
    plt.show()
    
def main():
    k=3
    print ("----------ing-------------")
    iris_data = load_iris()
    data= iris_data.data[:]
    clusterCenter,sampleTag,SSE = kMeans_way(data,k)
    if np.isnan(clusterCenter).any():
        print ("Error!reson:质心重叠!")
        return
    print (type(sampleTag))
    draw_pic(data,sampleTag,clusterCenter)
    print ("----------end-------------")

main()

在这里插入图片描述
思路,随机生成聚类中心。
然后,比较样本点到距离聚类中心的距离大小,距离哪个样本点近就属于哪个聚类。
随之,画出样本点及聚类中心。

标签:minJ,Kmeans,clusterCenter,range,聚类,np,import,鸢尾花
来源: https://blog.csdn.net/qq_38641985/article/details/112181842