python实现mean-shift聚类算法


Posted in Python onJune 10, 2020

本文实例为大家分享了python实现mean-shift聚类算法的具体代码,供大家参考,具体内容如下

1、新建MeanShift.py文件

import numpy as np

# 定义 预先设定 的阈值
STOP_THRESHOLD = 1e-4
CLUSTER_THRESHOLD = 1e-1


# 定义度量函数
def distance(a, b):
 return np.linalg.norm(np.array(a) - np.array(b))


# 定义高斯核函数
def gaussian_kernel(distance, bandwidth):
 return (1 / (bandwidth * np.sqrt(2 * np.pi))) * np.exp(-0.5 * ((distance / bandwidth)) ** 2)


# mean_shift类
class mean_shift(object):
 def __init__(self, kernel=gaussian_kernel):
  self.kernel = kernel

 def fit(self, points, kernel_bandwidth):

  shift_points = np.array(points)
  shifting = [True] * points.shape[0]

  while True:
   max_dist = 0
   for i in range(0, len(shift_points)):
    if not shifting[i]:
     continue
    p_shift_init = shift_points[i].copy()
    shift_points[i] = self._shift_point(shift_points[i], points, kernel_bandwidth)
    dist = distance(shift_points[i], p_shift_init)
    max_dist = max(max_dist, dist)
    shifting[i] = dist > STOP_THRESHOLD

   if(max_dist < STOP_THRESHOLD):
    break
  cluster_ids = self._cluster_points(shift_points.tolist())
  return shift_points, cluster_ids

 def _shift_point(self, point, points, kernel_bandwidth):
  shift_x = 0.0
  shift_y = 0.0
  scale = 0.0
  for p in points:
   dist = distance(point, p)
   weight = self.kernel(dist, kernel_bandwidth)
   shift_x += p[0] * weight
   shift_y += p[1] * weight
   scale += weight
  shift_x = shift_x / scale
  shift_y = shift_y / scale
  return [shift_x, shift_y]

 def _cluster_points(self, points):
  cluster_ids = []
  cluster_idx = 0
  cluster_centers = []

  for i, point in enumerate(points):
   if(len(cluster_ids) == 0):
    cluster_ids.append(cluster_idx)
    cluster_centers.append(point)
    cluster_idx += 1
   else:
    for center in cluster_centers:
     dist = distance(point, center)
     if(dist < CLUSTER_THRESHOLD):
      cluster_ids.append(cluster_centers.index(center))
    if(len(cluster_ids) < i + 1):
     cluster_ids.append(cluster_idx)
     cluster_centers.append(point)
     cluster_idx += 1
  return cluster_ids

2、调用上述py文件

# -*- coding: utf-8 -*-
"""
Created on Tue Oct 09 11:02:08 2018

@author: muli
"""

from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt 
import random
import numpy as np
import MeanShift


def colors(n):
 ret = []
 for i in range(n):
 ret.append((random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)))
 return ret

def main():
 centers = [[-1, -1], [-1, 1], [1, -1], [1, 1]]
 X, _ = make_blobs(n_samples=300, centers=centers, cluster_std=0.4)

 mean_shifter = MeanShift.mean_shift()
 _, mean_shift_result = mean_shifter.fit(X, kernel_bandwidth=0.5)

 np.set_printoptions(precision=3)
 print('input: {}'.format(X))
 print('assined clusters: {}'.format(mean_shift_result))
 color = colors(np.unique(mean_shift_result).size)

 for i in range(len(mean_shift_result)):
  plt.scatter(X[i, 0], X[i, 1], color = color[mean_shift_result[i]])
 plt.show()


if __name__ == '__main__':
 main()

结果如图所示:

python实现mean-shift聚类算法

参考链接

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python采用getopt解析命令行输入参数实例
Sep 30 Python
Python易忽视知识点小结
May 25 Python
python ansible服务及剧本编写
Dec 29 Python
django在接受post请求时显示403forbidden实例解析
Jan 25 Python
详解pyenv下使用python matplotlib模块的问题解决
Nov 29 Python
python队列Queue的详解
May 10 Python
python多线程下信号处理程序示例
May 31 Python
python excel转换csv代码实例
Aug 26 Python
详解使用Python写一个向数据库填充数据的小工具(推荐)
Sep 11 Python
python从Oracle读取数据生成图表
Oct 14 Python
python 基于selenium实现鼠标拖拽功能
Dec 24 Python
pytorch 如何把图像数据集进行划分成train,test和val
May 31 Python
Keras之自定义损失(loss)函数用法说明
Jun 10 #Python
Python xlwt模块使用代码实例
Jun 10 #Python
python中def是做什么的
Jun 10 #Python
keras实现调用自己训练的模型,并去掉全连接层
Jun 09 #Python
Python基于os.environ从windows获取环境变量
Jun 09 #Python
新手学习Python2和Python3中print不同的用法
Jun 09 #Python
Python基于wordcloud及jieba实现中国地图词云图
Jun 09 #Python
You might like
PHP服务器页面间跳转实现方法
2012/08/02 PHP
PHP6 中可能会出现的新特性预览
2014/04/04 PHP
Zend Framework教程之Zend_Controller_Plugin插件用法详解
2016/03/07 PHP
php file_get_contents取文件中数组元素的方法
2017/04/01 PHP
jQuery Div中加载其他页面的实现代码
2009/02/27 Javascript
比Jquery的document.ready更快的方法
2010/04/28 Javascript
JS实现图片预加载无需等待
2012/12/21 Javascript
javascript框架设计读书笔记之种子模块
2014/12/02 Javascript
深入分析jsonp协议原理
2015/09/26 Javascript
JS制作适用于手机和电脑的通知信息效果
2016/10/28 Javascript
angularjs定时任务的设置与清除示例
2017/06/02 Javascript
[js高手之路]原型式继承与寄生式继承详解
2017/08/28 Javascript
js实现复制功能(多种方法集合)
2018/01/06 Javascript
vue axios请求超时的正确处理方法
2018/04/02 Javascript
Vue.js上传图片到阿里云OSS存储的方法示例
2018/12/13 Javascript
微信小程序实现上传多个文件 超过10个
2020/03/30 Javascript
[52:31]VP vs Serenity 2018国际邀请赛小组赛BO2 第二场 8.16
2018/08/17 DOTA
Python配置文件解析模块ConfigParser使用实例
2015/04/13 Python
python实现二维插值的三维显示
2018/12/17 Python
python修改txt文件中的某一项方法
2018/12/29 Python
解决python3 requests headers参数不能有中文的问题
2019/08/21 Python
Linux下通过python获取本机ip方法示例
2019/09/06 Python
Python @property使用方法解析
2019/09/17 Python
python中实现词云图的示例
2020/12/19 Python
CSS3盒子模型详解
2013/04/24 HTML / CSS
英文简历中的自荐信范文
2013/12/14 职场文书
2014信息公开实施方案
2014/02/22 职场文书
党课培训主持词
2014/04/01 职场文书
新课培训心得体会
2014/09/03 职场文书
我爱家乡演讲稿
2014/09/12 职场文书
2014年底工作总结
2014/12/15 职场文书
2014收银员工作总结范文
2014/12/16 职场文书
教师个人年度总结
2015/02/11 职场文书
CSS3 菱形拼图实现只旋转div 背景图片不旋转功能
2021/03/30 HTML / CSS
Centos环境下Postgresql 安装配置及环境变量配置技巧
2021/05/18 PostgreSQL
Navicat for MySQL的使用教程详解
2021/05/27 MySQL