聚类--K均值算法:自主实现与sklearn.cluster.KMeans调用

import numpy as np

x = np.random.randint(1, 100, [20, 1])
y = np.zeros(20)
k = 3


# 选取数据空间中的K个对象作为初始中心,每个对象代表一个聚类中心;
def initcenter(x, k):  
    return x[0:k].reshape(k)


def nearest(kc, i):  
    a = (abs(kc - i))
    b= np.where(a == np.min(a))
    return b[0][0]


def xclassify(x, y, kc):
    for i in range(x.shape[0]):  
        y[i] = nearest(kc, x[i])
    return y


# 更新聚类中心:将每个类别中所有对象所对应的均值作为该类别的聚类中心,计算目标函数的值;
def kcmean(x, y, kc, k):  
    l = list(kc)
    flag = False
    for a in range(k):
        print(a)
        m = np.where(y == a)
        n = np.mean(x[m])
        if l[a] != n:
            l[a] = n
            flag = True  
            print(l, flag)
    return (np.array(l), flag)


k = 3
kc = initcenter(x, k)
flag = True
print(x, y, kc, flag)

# 判断聚类中心和目标函数的值是否发生改变,若不变,则输出结果,若改变,则返回2
while flag:
    y = xclassify(x, y, kc)
    kc, flag = kcmean(x, y, kc, k)
    print(y, kc, type(kc))

print(x, y)

import matplotlib.pyplot as plt

plt.scatter(x, x, c=y, s=50, cmap="rainbow");
plt.show()

 

#用sklearn.cluster.KMeans,鸢尾花花瓣长度数据做聚类并用散点图显示
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_iris

iris = load_iris()
a = iris.data
a

from sklearn.cluster import KMeans

est = KMeans(n_clusters = 3)
est.fit(a)
kc = est.cluster_centers_
y_kmeans = est.predict(a)  

print(y_kmeans,kc)
print(kc.shape,y_kmeans.shape,np.shape)

plt.scatter(a[:,0],a[:,1],c=y_kmeans,s=50,cmap='rainbow');
plt.show()

转载于:https://www.cnblogs.com/a1234tt/p/9886179.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值