首页 > 其他分享 >简单的手写kmeans

简单的手写kmeans

时间:2022-11-09 10:26:42浏览次数:44  
标签:center classfity kmeans new 简单 np 质心 手写 data

k=2
data = np.random.randn(100,2)
data[:50]+=2.0
center_index = np.random.choice(np.arange(len(data)), k)
center = data[center_index]

iters = 20
def dispatch(data,center):
    # n*2
    # k*2
    data = data[None]
    center = center[:,None]
    distance = ((data-center)**2).sum(axis= 2)
    return distance.argmin(axis=0)
threshold = 0.01
finsh = True
while finsh:
    classfity = dispatch(data,center)
    unique_classfity = np.unique(classfity)
    new_center = []
    for i in range(len(unique_classfity)):
        if np.any(new_center):
            data_vs = data[classfity==i].mean(axis = 0,keepdims = True)
            new_center = np.vstack((new_center,data_vs))
        else:
            new_center = data[classfity==i].mean(axis = 0,keepdims = True)
    diff = ((new_center - center) ** 2).sum()
    finsh=diff>threshold
    center = new_center
    print(f"diff:{diff:.5f}")
View Code - 1.指定K个初始质心 - 2.利用质心对数据进行分类 - 3.对分类后的数据,计算其质心,称之为新质心 - 4.判断新质心与当前质心之间的差距,是否小于指定阈值,如果成立则跳出 - 如果不成立,则替换当前质心为新的质心 - 执行2步骤 - 5.输出最后得到的质心

标签:center,classfity,kmeans,new,简单,np,质心,手写,data
From: https://www.cnblogs.com/xiaoruirui/p/16872670.html

相关文章

  • 手写一个Redux,深入理解其原理-面试进阶
    Redux可是一个大名鼎鼎的库,很多地方都在用,我也用了几年了,今天这篇文章就是自己来实现一个Redux,以便于深入理解他的原理。我们还是老套路,从基本的用法入手,然后自己实现一个R......
  • 【Python】Python环境安装与简单代码运行
    Python环境安装与简单代码运行一、配置Python环境1.下载Python安装包建议使用Python3.8版本,Win7、Win8、Win10、Win11都能用。(1)Python官网下载:网站:www.python.orgPyt......
  • grafana agent 动态配置内部机制简单说明
    grafanaagent动态配置目前属于一个体验特性,但是设计上利用了gomplate一个强大的模版引擎工具参考配置运行配置参考agentv2:image:grafana/agent:ma......
  • SpringCloud实现简单的远程服务调用
    一、服务的提供者。1、Spring脚手架创建工程。填写项目信息: 添加web依赖: 添加MyBatis依赖: 填写项目位置: 生成的项目结构:  pom.xml文件中的依赖也自动......
  • 链表简单实现
    #include<stdlib.h>#include<stdio.h>#include<stdbool.h>#include<time.h>/*该链表不带头节点第一个节点下标从0开始*/#defineElementTypeint#defineERRO......
  • 【Leetcode】 剑指offer:链表(简单)--Day02
    剑指Offer06.从尾到头打印链表可借助栈。或先遍历列表得到元素数,开辟数组空间倒序填入。剑指Offer24.反转链表可借助栈:classSolution{publicListNodere......
  • 使用PyTorch实现简单的AlphaZero的算法(1):背景和介绍
    在本文中,我们将在PyTorch中为ChainReaction[2]游戏从头开始实现DeepMind的AlphaZero[1]。为了使AlphaZero的学习过程更有效,我们还将使用一个相对较新的改进,称为“Playout......
  • jquery实现简单富文本编辑
      <script>$("#under").click(function(){varsec=getSelection()if(sec==undefined){return;......
  • Nexus搭建maven仓库并简单使用
    一、基本介绍参考:https://www.hangge.com/blog/cache/detail_2844.html1、为什么搭建私服如果没有私服,需要的构件都需要通过maven的中央仓库或者第三方的maven仓库下载......
  • javaScript简单的赋值运算符
    <----------------------------------------------赋值运算符------------------------------------------------------------>=号是赋值操作+=是加等于号,和(n=n+1)是......