K-means测试
一、实验目的
加深聚类算法的理解
熟悉K-means
二、实验环境
Windows + Python3+
一台装有集成开发环境(IDE)—— PyCharm的计算机
三、实验内容
1.根据已有的数据来进行聚类。
四、代码填写
import random
import math
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
plt.rcParams['figure.figsize'] = (10, 10) # 图像显示大小
plt.rcParams['font.sans-serif']=['SimHei'] #防止中文标签乱码,还有通过导入字体文件的方法
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['lines.linewidth'] = 0.5 #设置曲线线条宽度
#创建KMeans类
class KMeans():
def __init__(self):
self.data=None
self.k=2
self.partition=[]
self.dim=0
self.centers=[]
#train函数,用于训练
def train(self,classes=2,dim=2,trainData=None):
self.data=trainData
self.k=classes
self.dim=dim
random.shuffle(self.data)
for i in range(self.k):
self.centers.append([self.data[i]])
self.partition.append([self.data[i]])
while True:
plt.clf()
temp=self.centers
for example in self.data:
#挑出最近的点
best=self.Select(self.centers,example)
self.partition[best].append(example)
self.centers = self.Center(self.partition)
print(temp)
if temp==self.centers:
print(self.centers)
break
px = [a[0] for a in self.partition[0]]
py = [a[1] for a in self.partition[0]]
kx = [a[0] for a in self.partition[1]]
ky = [a[1] for a in self.partition[1]]
cx = [a[0][0] for a in self.centers]
cy = [a[0][1] for a in self.centers]
#画出迭代过程
plt.scatter(px, py, c="red")
plt.scatter(kx, ky, c="yellow")
plt.scatter(cx, cy, c='blue')
plt.pause(2)
self.partition = [[], []]
#计算中心位置
def Center(self,partition):
centers=[]
for points in partition:
tt=[]
temp=np.zeros(self.dim)
for point in points:
temp=temp+point
center=temp/len(points)
tt.append(list(center))
centers.append(tt)
return centers
#根据计算结果进行测试
def Test(self,testData=None):
result=[]
for example in testData:
best = self.Select(self.centers, example)
result.append(best)
print(result)
#计算距离
def calcuDis(self,a,b):
sum=0
for i in range(self.dim):
sum=sum+pow(a[i]-b[i],2)
return math.sqrt(sum)
#排序挑出最近的点
def Select(self,data,example):
centers=self.Center(data)
disLis=[]
for center in centers:
disLis.append(self.calcuDis(center[0],example))
ans = sorted(range(len(disLis)), key=lambda k: disLis[k])[0]
return ans
#自定义生成点集
def generate(num):
data=[]
for i in range(num):
x=list(np.random.randint(low=1,high=5*num)*np.random.randn(num,2))
x=[list(i) for i in x]
data.extend(x)
return data
km=KMeans()
data=[[0.697,0.460],
[0.774,0.376],
[0.634,0.264],
[0.608,0.318],
[0.556,0.215],
[0.403,0.237],
[0.481,0.149],
[0.437,0.211],
[0.666,0.091],
[0.243,0.267]]
km.train(classes=2,trainData=data,dim=2)
plt.ioff() # 关闭画图的窗口,即关闭交互模式
plt.show() # 显示图片,防止闪退
五、实验结果
给定数据测试
自定义数据集测试,动态演示