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

本文详细介绍了K均值算法的实现过程,并通过鸢尾花数据集进行聚类分析,展示了如何使用Python从零开始实现K均值算法,以及如何利用sklearn库进行聚类和可视化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.用python实现K均值算法

K-means是一个反复迭代的过程,算法分为四个步骤:

  (x,k,y)

1) 选取数据空间中的K个对象作为初始中心,每个对象代表一个聚类中心;

  def initcenter(x, k): kc

2) 对于样本中的数据对象,根据它们与这些聚类中心的欧氏距离,按距离最近的准则将它们分到距离它们最近的聚类中心(最相似)所对应的类;

  def nearest(kc, x[i]): j

  def xclassify(x, y, kc):y[i]=j

3) 更新聚类中心:将每个类别中所有对象所对应的均值作为该类别的聚类中心,计算目标函数的值;

  def kcmean(x, y, kc, k):

4) 判断聚类中心和目标函数的值是否发生改变,若不变,则输出结果,若改变,则返回2)。

  while flag:

      y = xclassify(x, y, kc)

      kc, flag = kcmean(x, y, kc, k)

2. 鸢尾花花瓣长度数据做聚类并用散点图显示。

3. 用sklearn.cluster.KMeans,鸢尾花花瓣长度数据做聚类并用散点图显示.

4. 鸢尾花完整数据做聚类并用散点图显示.

#1.用python实现K均值算法
#K-means是一个反复迭代的过程,算法分为四个步骤:
import numpy as np
x = np.random.randint(1,50,[20,1])
y = np.zeros(20)
k = 3

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

#2) 对于样本中的数据对象,根据它们与这些聚类中心的欧氏距离,按距离最近的准则将它们分到距离它们最近的聚类中心(最相似)所对应的类;
def nearest(kc,i):
    d = abs(kc -i)
    w = np.where(d == np.min(d))
    return w[0][0]

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

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

#4) 判断聚类中心和目标函数的值是否发生改变,若不变,则输出结果,若改变,则返回2)

kc = initcenter(x,k)
flag = True
print(x,y,kc,flag)
while flag:
    y = xclassify(x,y,kc)
    kc,flag = kcmean(x,y,kc,k)
print(y,kc)

  

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

iris = load_iris()
x = iris.data[:, 1]
y = np.zeros(150)

def initcent(x, k):  # 初始聚类中心数组
    return x[0:k].reshape(k)

def nearest(kc, i):  # 数组中的值,与聚类中心最小距离所在类别的索引号
    d = (abs(kc - i))
    w = np.where(d == np.min(d))
    return w[0][0]

def kcmean(x, y, kc, k):  # 计算各聚类新均值
    l = list(kc)
    flag = False
    for c in range(k):
        m = np.where(y == c)
        n = np.mean(x[m])
        if l[c] != n:
            l[c] = n
            flag = True  # 聚类中心发生变化
    return (np.array(l), flag)

def xclassify(x, y, kc):
    for i in range(x.shape[0]):  # 对数组的每个值分类
        y[i] = nearest(kc, x[i])
    return y

k = 3
kc = initcent(x, k)
flag = True
print(x, y, kc, flag)
while flag:
    y = xclassify(x, y, kc)
    kc, flag = kcmean(x, y, kc, k)
print(y, kc, type(kc))

import matplotlib.pyplot as plt
plt.scatter(x,x,c=y,s=50,cmap='rainbow',marker='p',alpha=0.5)
plt.show()

  

#3.用sklearn.cluster.KMeans,鸢尾花完整数据做聚类并用散点图显示.
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_iris
iris=load_iris()
print(iris)
X=iris.data
print(X)
from sklearn.cluster import KMeans
est = KMeans(n_clusters=3)
est.fit(X)
kc = est.cluster_centers_
y_kmeans = est.predict(X) #预测每个样本的聚类索引
print(y_kmeans,kc)
print(kc.shape,y_kmeans.shape)
plt.scatter(X[:,0],X[:,1],c=y_kmeans,s=50,cmap='rainbow')
plt.show()

  

#4. 鸢尾花完整数据做聚类并用散点图显示.
from sklearn.cluster import KMeans
import numpy as np
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
data = load_iris()
iris = data.data
petal_len = iris
print(petal_len)
k_means = KMeans(n_clusters=3) #三个聚类中心
result = k_means.fit(petal_len) #Kmeans自动分类
kc = result.cluster_centers_ #自动分类后的聚类中心
y_means = k_means.predict(petal_len) #预测Y值
plt.scatter(petal_len[:,0],petal_len[:,2],c=y_means, marker='p',cmap='rainbow')
plt.show()

  

 

转载于:https://www.cnblogs.com/ljy28/p/9942154.html

本程序是在python中完成,基于sklearn.cluster中的k-means聚类包来实现数据的聚类,对于里面使用的数据格式如下:(注意更改程序中的相关参数) 138 0 124 1 127 2 129 3 119 4 127 5 124 6 120 7 123 8 147 9 188 10 212 11 229 12 240 13 240 14 241 15 240 16 242 17 174 18 130 19 132 20 119 21 48 22 37 23 49 0 42 1 34 2 26 3 20 4 21 5 23 6 13 7 19 8 18 9 36 10 25 11 20 12 19 13 19 14 5 15 29 16 22 17 13 18 46 19 15 20 8 21 33 22 41 23 69 0 56 1 49 2 40 3 52 4 62 5 54 6 32 7 38 8 44 9 55 10 70 11 74 12 105 13 107 14 56 15 55 16 65 17 100 18 195 19 136 20 87 21 64 22 77 23 61 0 53 1 47 2 33 3 34 4 28 5 41 6 40 7 38 8 33 9 26 10 31 11 31 12 13 13 17 14 17 15 25 16 17 17 17 18 14 19 16 20 17 21 29 22 44 23 37 0 32 1 34 2 26 3 23 4 25 5 25 6 27 7 30 8 25 9 17 10 12 11 12 12 12 13 7 14 6 15 6 16 12 17 12 18 39 19 34 20 32 21 34 22 35 23 33 0 57 1 81 2 77 3 68 4 61 5 60 6 56 7 67 8 102 9 89 10 62 11 57 12 57 13 64 14 62 15 69 16 81 17 77 18 64 19 62 20 79 21 75 22 57 23 73 0 88 1 75 2 70 3 77 4 73 5 72 6 76 7 76 8 74 9 98 10 90 11 90 12 85 13 79 14 79 15 88 16 88 17 81 18 84 19 89 20 79 21 68 22 55 23 63 0 62 1 58 2 58 3 56 4 60 5 56 6 56 7 58 8 56 9 65 10 61 11 60 12 60 13 61 14 65 15 55 16 56 17 61 18 64 19 69 20 83 21 87 22 84 23 41 0 35 1 38 2 45 3 44 4 49 5 55 6 47 7 47 8 29 9 14 10 12 11 4 12 10 13 9 14 7 15 7 16 11 17 12 18 14 19 22 20 29 21 23 22 33 23 34 0 38 1 38 2 37 3 37 4 34 5 24 6 47 7 70 8 41 9 6 10 23 11 4 12 15 13 3 14 28 15 17 16 31 17 39 18 42 19 54 20 47 21 68 22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值