Python机器学习之K聚类算法

这段代码展示了如何利用K均值聚类算法对鸢尾花数据集进行分类,并通过三维可视化展示聚类结果。首先,从CSV文件中读取数据并转换为浮点数格式,然后随机选择三个点作为初始中心点。接着,根据欧氏距离将数据点分配到最近的类别,并计算每个类别新的中心点。这个过程不断迭代,直到类别不再变化。最后,使用matplotlib库将三个类别在三维空间中分别用不同颜色的点表示出来。
摘要由CSDN通过智能技术生成

K聚类的作用:

对于给定的数据集通过欧式距离进行分类

假定对给定的数据集分成3类

算法步骤 

1 读取数据集,将数据集读取成矩阵

2 随机在矩阵中找三个点A,B, C作为中心点

3 计算每一个到三个中心点的距离,将该点归到距离最近的中心点,最终分成A,B,C三类

4 将已归好的三类求每类的平均值作为新的中心点记为A1,B1,C1

5 重复3与4步骤直至分的3类不在发生改变

数据集文件

链接:https://pan.baidu.com/s/1uBya2epJuiqYC5K8DSkImw 
提取码:4y28

代码如下


import csv
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # 空间三维画图
import time

start = time.time()


#读取csv文件
# 对utf-8编码
def readCSV_UTF8(path):
    with open(path, "r", encoding='UTF-8') as file:
        data = csv.reader(file)
        list = []
        for row in data:
            list.append(row)
    return list


# 对gbk编码
def readCSV_gbk(path):
    with open(path, "r") as file:  # gbk
        data = csv.reader(file)
        list = []
        for row in data:
            list.append(row)
    return list


list = readCSV_UTF8("iris.csv")  #此时LIST列表中是字符

list.pop(0)
for i in range(len(list)):
    list[i] = list[i][:4]
#将字符转化成浮点数方便运算
for i in range(len(list)):
    for j in range(len(list[i])):
        list[i][j] = float(list[i][j])

data = np.array(list)   #data是矩阵

def distE(zhidian, list):   #距离计算函数  计算欧氏距离
    if len(zhidian) != len(list):
        return False
    else:
        m = 0
        for i in range(len(list)):
            n = (list[i] - zhidian[i])**2
            m += n
    return m



#聚类函数
def cluster(x, y, z, list):
    list1 = []
    list2 = []
    list3 = []

    list1.append(x)
    list2.append(y)
    list3.append(z)

    for i in range(len(list)):
        if distE(x, list[i]) <= distE(y, list[i]) and distE(x, list[i]) <= distE(z, list[i]):
            list1.append(list[i])
        elif distE(y, list[i]) <= distE(x, list[i]) and distE(y, list[i]) <= distE(z, list[i]):
            list2.append(list[i])
        else:
            list3.append(list[i])

    return list1, list2, list3
#求质心函数
def centre(a, b, c):
    a = np.array(a)
    b = np.array(b)
    c = np.array(c)
    centre1 = np.sum(a, axis=0)/len(a)
    centre2 = np.sum(b, axis=0)/len(b)
    centre3 = np.sum(c, axis=0)/len(c)
    centre1 = centre1.tolist()
    centre2 = centre2.tolist()
    centre3 = centre3.tolist()
    return centre1, centre2, centre3


a,b,c =cluster(list[1], list[50], list[149], list)
centre1, centre2, centre3 = centre(a,b,c)
'''test_list = []
test_list.append(centre1)
test_list.append(centre2)
test_list.append(centre3)'''
#进行循环迭代
for i in range(100):   #这里应该用while循环,但是我用while老是报错所以麻烦了一些用的for循环
    if i == 0:
        list1, list2, list3 = cluster(centre1, centre2, centre3, list)
        m, n, p = centre(list1, list2, list3)
    else:
        list1, list2, list3 = cluster(m, n, p, list)
        m, n, p = centre(list1, list2, list3)
        '''test_list.append(m)
        test_list.append(n)
        test_list.append(p)
    if ((test_list[len(test_list)] == test_list[len(test_list)-3]) &
        (test_list[len(test_list)-1] == test_list[len(test_list)-4]) &
        (test_list[len(test_list)-2] == test_list[len(test_list)-5])):
        break
    else:
        pass'''

array1 = np.array(list1)
array2 = np.array(list2)
array3 = np.array(list3)



#将数据可视化
x1 = array1[:, 0]
y1 = array1[:, 1]
z1 = array1[:, 2]
x2 = array2[:, 0]
y2 = array2[:, 1]
z2 = array2[:, 2]
x3 = array3[:, 0]
y3 = array3[:, 1]
z3 = array3[:, 2]
fig = plt.figure()  #创建一个图
#ax = fig.add_subplot(111, projection='3d')
ax = Axes3D(fig)

ax.scatter(x1, y1, z1, c = 'r', marker='o', s=100*array1[:, 3])
ax.scatter(x2, y2, z2, c = 'b', marker='o', s=100*array2[:, 3])
ax.scatter(x3, y3, z3, c = 'y', marker='o', s=100*array3[:, 3])

x0 = data[:, 0]
y0 = data[:, 1]
z0 = data[:, 2]
fig = plt.figure()  #创建一个图
ax = Axes3D(fig)
ax.scatter(x0, y0, z0)
end = time.time()
print(end - start)



plt.show()












本程序是在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、付费专栏及课程。

余额充值