机器学习 K-means,聚类算法(简版) 分为两个聚类(两个簇)

@K-means,聚类算法(简) 分为两个聚类

用的是Spyder编辑器
用到绘图库
和numpy


import numpy as np
import matplotlib.pyplot as plt

x=np.array([[1,2],[1.5,1.8],[5,8],[8,8],[1,0.6],[9,10]])
np.random.seed(5)
x=np.random.rand(10000).reshape(-1,2)

k=2
medoids=[x[1],x[2]]
max_iter=100
for t in range(max_iter): #迭代次数
    
    cluster1=[]
    cluster2=[]
    
    #计算所有点与中心点的距离,根据就近原则将点分配到最近的那个中心所对应的簇
    for i in range(len(x)): 
        d1=np.sum(np.square(x[i]-medoids[0]))
        d2=np.sum(np.square(x[i]-medoids[1]))
        if d1<=d2:
            cluster1.append(x[i])
        else:
            cluster2.append(x[i])
            
    
    medoids=[np.mean(cluster1,axis=0),np.mean(cluster2,axis=0)]    
    print(medoids)
    
cluster1=np.array(cluster1)
cluster2=np.array(cluster2)
plt.plot(cluster1[:,0],cluster1[:,1],'r*')
plt.plot(cluster2[:,0],cluster2[:,1],'g*')

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值