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 fabric使用笔记
May 09 Python
Python编程之属性和方法实例详解
May 19 Python
Python的爬虫包Beautiful Soup中用正则表达式来搜索
Jan 20 Python
Python用模块pytz来转换时区
Aug 19 Python
详解python开发环境搭建
Dec 16 Python
完美解决Pycharm无法导入包的问题 Unresolved reference
May 18 Python
Django框架自定义session处理操作示例
May 27 Python
更新pip3与pyttsx3文字语音转换的实现方法
Aug 08 Python
基于 Django 的手机管理系统实现过程详解
Aug 16 Python
解决Djang2.0.1中的reverse导入失败的问题
Aug 16 Python
kafka-python 获取topic lag值方式
Dec 23 Python
Python 如何将integer转化为罗马数(3999以内)
Jun 05 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 array_unique之后json_encode需要注意
2011/01/02 PHP
php实现文件下载更能介绍
2012/11/23 PHP
CodeIgniter扩展核心类实例详解
2016/01/20 PHP
php实现的顺序线性表示例
2019/05/04 PHP
javascript+dom树型菜单类,希望朋友们一起进步
2007/05/03 Javascript
犀利的js 函数集合
2009/06/11 Javascript
Extjs学习过程中新手容易碰到的低级错误积累
2010/02/11 Javascript
jQuery实现form表单reset按钮重置清空表单功能
2012/12/18 Javascript
javascript实现2048游戏示例
2014/05/04 Javascript
jQuery 获取/设置/删除DOM元素的属性以a元素为例
2014/05/23 Javascript
10分钟学会写Jquery插件实例教程
2014/09/06 Javascript
修改Jquery Dialog 位置的实现方法
2016/08/26 Javascript
详解Node.js实现301、302重定向服务
2017/04/07 Javascript
实现两个文本框同时输入的实例
2017/09/25 Javascript
koa+mongoose实现简单增删改查接口的示例代码
2019/05/13 Javascript
微信小程序实现卡片层叠滑动效果
2019/06/21 Javascript
layui在form表单页面通过Validform加入简单验证的方法
2019/09/06 Javascript
在vue中使用防抖和节流,防止重复点击或重复上拉加载实例
2019/11/13 Javascript
[02:19]2018年度DOTA2最佳核心位选手-完美盛典
2018/12/17 DOTA
Python的词法分析与语法分析
2013/05/18 Python
python中使用序列的方法
2015/08/03 Python
Python调用微信公众平台接口操作示例
2017/07/08 Python
python文件特定行插入和替换实例详解
2017/07/12 Python
用matplotlib画等高线图详解
2017/12/14 Python
Puppeteer使用示例详解
2019/06/20 Python
python的mysql数据库建立表与插入数据操作示例
2019/09/30 Python
python 追踪except信息方式
2020/04/25 Python
一款html5 canvas实现的图片玻璃碎片特效
2014/09/11 HTML / CSS
哄娃神器4moms商店:美国婴童用品品牌
2019/03/07 全球购物
精美的手工家居和生活用品:Nkuku
2019/11/01 全球购物
社区国庆节活动方案
2014/02/05 职场文书
2014年党员公开承诺书范文
2014/03/28 职场文书
地理信息科学专业推荐信
2014/09/08 职场文书
2015年中秋晚会主持稿
2015/07/30 职场文书
毕业生入职感言
2015/07/31 职场文书
vue+iview实现手机号分段输入框
2022/03/25 Vue.js