k-means:是无监督的分类算法

k代表要分的类数,即要将数据聚为k类; means是均值,代表着聚类中心的迭代策略.

k-means算法思想:

(1)随机选取k个聚类中心(一般在样本集中选取,也可以自己随机选取);

(2)计算每个样本与k个聚类中心的距离,并将样本归到距离最小的那个类中;

(3)更新中心,计算属于k类的样本的均值作为新的中心。

(4)反复迭代(2)(3),直到聚类中心不发生变化,后者中心位置误差在阈值范围内,或者达到一定的迭代次数。

python实现:

k-means简单小样例:

import numpy as np

data = np.random.randint(1,10,(30,2))
#k=4
k=4
#central
np.random.shuffle(data)
cent = data[0:k,:]
#distance
distance = np.zeros((data.shape[0],k))
last_near = np.zeros(data.shape[0])
n=0
while True:
n = n+1
print(n)
for i in range(data.shape[0]):
for j in range(cent.shape[0]):
dist = np.sqrt(np.sum((data[i]-cent[j])**2))
distance[i,j] = dist
nearst = np.argmin(distance,axis = 1)
if (last_near == nearst).all():
#if n<1000:
break
#update central
for ele_cen in range(k):
cent[ele_cen] = np.mean(data[nearst == ele_cen],axis=0)
last_near = nearst
print(cent)
下面样例是为了适应yolov3选取anchorbox的度量需求:
import numpy as np

def iou(box, clusters):
"""
Calculates the Intersection over Union (IoU) between a box and k clusters.
:param box: tuple or array, shifted to the origin (i. e. width and height)
:param clusters: numpy array of shape (k, 2) where k is the number of clusters
:return: numpy array of shape (k, 0) where k is the number of clusters
"""
x = np.minimum(clusters[:, 0], box[0])
y = np.minimum(clusters[:, 1], box[1])
if np.count_nonzero(x == 0) > 0 or np.count_nonzero(y == 0) > 0:
raise ValueError("Box has no area")
intersection = x * y
box_area = box[0] * box[1]
cluster_area = clusters[:, 0] * clusters[:, 1]
iou_ = intersection / (box_area + cluster_area - intersection)
return iou_ def kmeans(boxes, k, dist=np.median):
"""
Calculates k-means clustering with the Intersection over Union (IoU) metric.
:param boxes: numpy array of shape (r, 2), where r is the number of rows
:param k: number of clusters
:param dist: distance function
:return: numpy array of shape (k, 2)
"""
rows = boxes.shape[0] distances = np.empty((rows, k)) #初始化距离矩阵,rows代表样本数量,k代表聚类数量,用于存放每个样本对应每个聚类中心的距离
last_clusters = np.zeros((rows,))#记录上一次样本所属的类型 np.random.seed() # the Forgy method will fail if the whole array contains the same rows
clusters = boxes[np.random.choice(rows, k, replace=False)]#从样本中随机选取聚类中心 while True:
for row in range(rows):
distances[row] = 1 - iou(boxes[row], clusters) #这里是距离计算公式,这里是为了适应yolov3选取anchorbox的度量需求
nearest_clusters = np.argmin(distances, axis=1) #找到距离最小的类
if (last_clusters == nearest_clusters).all(): #判断是否满足终止条件
break
for cluster in range(k): #更新聚类中心
clusters[cluster] = dist(boxes[nearest_clusters == cluster], axis=0) #将某一类的均值更新为聚类中心
last_clusters = nearest_clusters
return clusters 希望可以为正在疑惑的你提供一些思路!

k-means原理和python代码实现的更多相关文章

  1. 单链表反转的原理和python代码实现

    链表是一种基础的数据结构,也是算法学习的重中之重.其中单链表反转是一个经常会被考察到的知识点. 单链表反转是将一个给定顺序的单链表通过算法转为逆序排列,尽管听起来很简单,但要通过算法实现也并不是非常容 ...

  2. woe_iv原理和python代码建模

    python信用评分卡(附代码,博主录制) https://study.163.com/course/introduction.htm?courseId=1005214003&utm_camp ...

  3. 线性插值法的原理和python代码实现

    假设我们已知坐标 (x0, y0) 与 (x1, y1),要得到 [x0, x1] 区间内某一位置 x 在直线上的值.根据图中所示,我们得到 由于 x 值已知,所以可以从公式得到 y 的值 已知 y  ...

  4. 机器学习之感知器算法原理和Python实现

    (1)感知器模型 感知器模型包含多个输入节点:X0-Xn,权重矩阵W0-Wn(其中X0和W0代表的偏置因子,一般X0=1,图中X0处应该是Xn)一个输出节点O,激活函数是sign函数. (2)感知器学 ...

  5. 对数损失函数(Logarithmic Loss Function)的原理和 Python 实现

    原理 对数损失, 即对数似然损失(Log-likelihood Loss), 也称逻辑斯谛回归损失(Logistic Loss)或交叉熵损失(cross-entropy Loss), 是在概率估计上定 ...

  6. 常见素数筛选方法原理和Python实现

    1. 普通筛选(常用于求解单个素数问题) 自然数中,除了1和它本身以外不再有其他因数. import math def func_get_prime(n): func = lambda x: not ...

  7. 【集成学习】:Stacking原理以及Python代码实现

    Stacking集成学习在各类机器学习竞赛当中得到了广泛的应用,尤其是在结构化的机器学习竞赛当中表现非常好.今天我们就来介绍下stacking这个在机器学习模型融合当中的大杀器的原理.并在博文的后面附 ...

  8. 【LeetCode】1022. Smallest Integer Divisible by K 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  9. [转] Python 代码性能优化技巧

    选择了脚本语言就要忍受其速度,这句话在某种程度上说明了 python 作为脚本的一个不足之处,那就是执行效率和性能不够理想,特别是在 performance 较差的机器上,因此有必要进行一定的代码优化 ...

随机推荐

  1. LeetCode All in One 题目讲解汇总(转...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通 ...

  2. [数据结构] 2.3 Trie树

    抱歉更新晚了,看了几天三体,2333,我们继续数据结构之旅. 一.什么是Tire树? Tire树有很多名字:字典树.单词查找树. 故名思意,它就是一本”字典“,当我们查找"word" ...

  3. flutter SnackBar异常Another exception was thrown: Scaffold.of() called with a context that does not contain a Scaffold

    代码如下: import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'Returning Da ...

  4. 打印GC日志

    所需参数如下: -XX:+PrintGCTimeStamps -XX:+PrintGCDetails -verbose:gc -Xloggc:gc.log 会在根目录生成 gc.log 文件,里面记录 ...

  5. HTML——<body> 计算机代码 【头部在“网站开发”中】

    HTML属性 完整的属性列表 在引用属性值的时候,如果某些属性本身就有双引号——name= 'John "ShotGun" Nelson' 

  6. 应用安全 - 中间件 - Apache - Apache POI

    CVE-2014-3529 Date2014 类型 注入XML外部实体访问外部实体资源或者读取任意文件 影响范围 Apache POI 3.10-FINAL及以前版本 复现 CVE-2016-5000 ...

  7. 简述Vue的实例属性、实例方法

    1.实例属性 组件树访问 $parent -----> 用来访问当前组件实例的父实例: $root -----> 用来访问当前组件树的根实例,如果当前组件没有父实例,则$root表示当前组 ...

  8. python之optparse

    Python有两个内建的模块用来处理命令行参数 一个是getopt只能简单处理命令行参数 一个是optparse,功能更强大,而且易于使用,可以方便地生成标准的,符合Unix/Posix规范的命令行说 ...

  9. C++自学教程第一课——你好世界,我是柠檬鲸。

    C++系列教程现在在自己学校的一个博客平台发布,几个朋友一起搭建的 [C++基础教程系列](https://blog.ytmaxoj.org/cpp_basic_liuary-0/) 下面是原来的正文 ...

  10. Kotlin学习(5)类型系统

    可空性(避免空指针异常) /* *这个函数的参数代表传入一个String类型变量的实例,这代表它不可以为空 */ fun a(str:String){ println(str) } //这样调用a() ...