练习一:用python实现K均值算法

代码:

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

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

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

#用for循环遍历,把随机数组自动划分到与它距离最近的类,返回类的下标y
def xclassify(x,y,kc):
    for i in range(x.shape[0]):
        y[i] = nearest(kc,x[i])
        return y
    
#3) 更新聚类中心:将每个类别中所有对象所对应的均值作为该类别的聚类中心,计算目标函数的值
def kcmean(x,y,kc,k):
    l = list(kc)
    flag = False
    for c in range(k):
        m = np.where(y==c)
        if m[0].shape != (0,):
            n = np.mean(x[m])
        if l[c] != n:
            l[c] = n
            flag = True           
    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)

运行结果:

程序员数据挖掘 数据挖掘程序题_数据

练习二:鸢尾花花瓣长度数据做聚类并用散点图显示

代码;

import matplotlib.pyplot as plt
plt.scatter(x,x,c=x,s=50,cmap="rainbow");
plt.show()

运行结果:

程序员数据挖掘 数据挖掘程序题_聚类_02

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

代码:

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[:,2:3]

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,np.linspace(1,150,150),c=y_means,marker='x')

plt.show()

运行结果:

程序员数据挖掘 数据挖掘程序题_数据_03

练习四:鸢尾花完整数据做聚类并用散点图显示

代码:

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_iris

iris = load_iris()
X = iris.data
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,np.shape)

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

运行结果:

程序员数据挖掘 数据挖掘程序题_自动分类_04