首页 / 算法 / KMeans算法——python实现
KMeans算法——python实现
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了KMeans算法——python实现,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3857字,纯文字阅读大概需要6分钟。
内容图文
KMeans介绍
最基础的,常用的机器学习算法
k均值聚类算法是一种迭代求解的聚类分析算法。
聚类是无监督学习,将相似的对象归到一簇中,簇的对象越相似,效果越好。
优点
原理简单,容易实现
缺点
需要对K值进行指定,对初始的中心点选取较为敏感,初始的中心点影响了分类的结果
算法推导
本例子采用欧式距离算法,即两点之间的直线距离
用户需要对k值进行指定,k代表簇的个数
传入需要处理的数据,数据可以是任意维度的,个数可以是不确定的
对传入的数据随机选取k个作为中心点
遍历数据,把每个数据与中心点进行计算,把它归类为与之距离最近的点
计算每一类点的平均值,算出新的中心点
计算新的中心点与旧的中心点的平均距离,看平均距离是否符合误差范围,
符合就输出结果,不符合,就继续遍历
代码实现
import random
import copy
import matplotlib.pyplot as plt
class KMeans():
def __init__(self,data,k=1):
self.__data = data # 存放输入点数据
self.__k = k # 中心点个数
self.__centerPoint = [] # 中心点
self.__result = [] # 对输入点进行分类的结果
for i in range(k):
self.__result.append([]) #[[] [] [] [] [] ]
# 随机取k个中心点
def randomCenterPoint(self):
for i in range(self.__k):
# 随机出k个下标
index = random.randint(0,len(self.__data)-1)
# 判断取出的数是否在中心点中 防止取重复数 使中心点重复
if self.__data[index] not in self.__centerPoint:
self.__centerPoint.append(self.__data[index])
pass
# 把数据进行分类 计算各点到中心点的距离
# data为点数据
# center为中心点
def calCenterPointDistance(self, data, center):
centerDistance = [] # 用来记录每个点到k个中心点的距离[[k个数][k个数][k个数][k个数]...]长度为len(data)
# 计算并存储各点到中心点距离
for temp in data:
centerDistance.append([self.distance(temp,point) for point in center])
pass
self.__result = []
# 因为对result进行的使append操作 及时清空 否则数据会堆积 越来越多
# 对result清空操作
for i in range(self.__k):
self.__result.append([])
m = 0
# 根据各点到中心点距离 把数据点进行分类
for temp in centerDistance:
index = temp.index(min(temp))
self.__result[index].append(copy.deepcopy(data[m]))
m += 1
# 计算两点之间的距离 任何维度都可以
def distance(self,pointA,pointB):
distance = (sum([(x - y)**2 for x,y in zip(pointA,pointB)]))**0.5
return distance
pass
# 计算生成新的中心点
def newCenterPoint(self, result):
newCenterPoint = [] # 存放新的中心点
# 转置矩阵 把各点x,y ,z...放在同一数组 方便计算
for temp in result:
temps = [[x[i] for x in temp]for i in range(len(temp[0]))]
point = [] # 存放新中心点的x,y,z.... 临时变量
for t in temps:
point.append(sum(t)/len(t))
newCenterPoint.append(copy.deepcopy(point))
return newCenterPoint
# 计算新旧中心点之间的距离
# old代表原来的中心点列表 new新生成的中心点列表
def calCenterPointToCenterPointDistance(self, old, new):
total = 0
for point1, point2 in zip(old, new):
total += self.distance(point1, point2)
# 返回新旧点的误差值
return total/len(old) # new也行
pass
# 执行函数
def fit(self, threshold):
self.randomCenterPoint() # 随机中心点
self.calCenterPointDistance(self.__data, self.__centerPoint) # 把数据根据中心点分类
newCenterPoint = self.newCenterPoint(self.__result) # 生成新的中心点
oldCenterPoint = self.__centerPoint # 旧的中心点
# 程序结束的条件
while self.calCenterPointToCenterPointDistance(oldCenterPoint,newCenterPoint) > threshold:
self.calCenterPointDistance(self.__data, newCenterPoint) # 对data点数据进行新的分类
oldCenterPoint = newCenterPoint # 覆盖旧点
newCenterPoint = self.newCenterPoint(self.__result) # 生成新点
self.__centerPoint = newCenterPoint
return newCenterPoint, self.__result
if __name__ == "__main__":
# 生成x个随机点
data = [[random.randint(1, 100), random.randint(1, 100)]for i in range(1000)]
km = KMeans(data, 6)
center,result = km.fit(0.0001)
# 数据可视化 可清楚看见点的分布情况
plt.plot()
plt.title("KMeans Classification")
i = 0
tempx = []
tempy = []
color = []
for temp in result:
temps = [[temp[x][i] for x in range(len(temp))] for i in range(len(temp[0]))]
color += [i] * len(temps[0])
tempx += temps[0]
tempy += temps[1]
i += 2
pass
plt.scatter(tempx, tempy, c=color, s=30)
plt.show()
结果图
相同的数据每次运行分类结果也不同
内容总结
以上是互联网集市为您收集整理的KMeans算法——python实现全部内容,希望文章能够帮你解决KMeans算法——python实现所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。