Python手动实现k-means
import numpy as np
import matplotlib.pyplot as plt
def kmeans(data, cluster_num, method='mean'):
points = np.array(data)
labels = []
random_idx = []
while True:
t = np.random.randint(points.shape[0])
if t not in random_idx:
random_idx.append(t)
if len(random_idx) == cluster_num:
break
seeds = []
for i in range(cluster_num):
seeds.append(points[random_idx[i]])
seeds = np.array(seeds)
prev_seeds = seeds + 10
colors = ["red", "blue", "yellow", "cyan", "purple"]
points_labeled = []
for i in range(cluster_num):
points_labeled.append([])
while sum(abs((prev_seeds - seeds).ravel())) > 0:
prev_seeds = seeds.copy()
for i in range(points.shape[0]):
t_min = 10000
for j in range(seeds.shape[0]):
t_current = np.sqrt((points[i][0] - seeds[j][0]) ** 2 + (points[i][1] - seeds[j][1]) ** 2)
if t_current < t_min:
t_min = t_current
try:
labels.pop(i)
except IndexError:
pass
labels.append(j)
for i in range(len(labels)):
points_labeled[labels[i]].append(points[i].tolist())
points_labeled = np.array(points_labeled)
for i in range(points_labeled.shape[0]):
if points_labeled[i]:
plt.scatter(np.array(points_labeled[i])[:, 1], np.array(points_labeled[i])[:, 0], c=colors[i])
for i in seeds:
plt.scatter(i[1], i[0], c="black", linewidths=3)
plt.show()
for i in range(seeds.shape[0]):
if method == 'mean':
seeds[i] = np.array(
[np.mean(np.array(points_labeled[i])[:, 0]), np.mean(np.array(points_labeled[i])[:, 1])])
elif method == 'median':
seeds[i] = np.array(
[np.median(np.array(points_labeled[i])[:, 0]), np.median(np.array(points_labeled[i])[:, 1])])
points_labeled = []
for i in range(cluster_num):
points_labeled.append([])
labels = []
return seeds, labels, sum(abs((prev_seeds - seeds).ravel()))
if __name__ == "__main__":
points = [
[2, 4], [4, 2], [6, 2], [5, 3], [5, 5], [7, 5],
[5, 15], [6, 17], [4, 14], [5, 13], [9, 15], [3, 14], [7, 13],
[20, 16], [19, 15], [17, 15], [16, 14], [14, 18], [22, 10], [17, 17], [16, 13], [18, 14], [17, 13],
[22, 26], [24, 23], [25, 25], [26, 22], [26, 26], [26, 28], [28, 18], [28, 28]
]
cluster_num = 4
[centroids, labels, interia] = kmeans(points, cluster_num)
Python手动实现k-means的更多相关文章
- Python实现kMeans(k均值聚类)
Python实现kMeans(k均值聚类) 运行环境 Pyhton3 numpy(科学计算包) matplotlib(画图所需,不画图可不必) 计算过程 st=>start: 开始 e=> ...
- 软件——机器学习与Python,聚类,K——means
K-means是一种聚类算法: 这里运用k-means进行31个城市的分类 城市的数据保存在city.txt文件中,内容如下: BJ,2959.19,730.79,749.41,513.34,467. ...
- Python手动构造Cookie模拟登录后获取网站页面内容
最近有个好友让我帮忙爬取个小说,这个小说是前三十章直接可读,后面章节需要充值VIP可见.所以就需要利用VIP账户登录后,构造Cookie,再用Python的获取每章节的url,得到内容后再使用 PyQ ...
- python dash 初探 --- k 线国内版
python dash 的应用首页,是用一个 k 线图来做 damo 的,奈何数据源用的 Google,上不去.当然,可以换 yahoo,但是毕竟国内的还是更亲切些. 官方的 demo 用的 pand ...
- 用Python从零开始实现K近邻算法
KNN算法的定义: KNN通过测量不同样本的特征值之间的距离进行分类.它的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别.K通 ...
- 『OpenCV3』Harris角点特征_API调用及python手动实现
一.OpenCV接口调用示意 介绍了OpenCV3中提取图像角点特征的函数: # coding=utf- import cv2 import numpy as np '''Harris算法角点特征提取 ...
- python入门1 python手动编译py_compile,compileall
python运行之后会自动生产pyc文件,也可以手动编译生成pyc文件.代码如下: #coding:utf-8 """ 2018-11-03 dinghanhua 手动编 ...
- python 手动安装模块
python中 openpyxl是解析 excel 文件的模块,一般使用pip install openpyxl 就可以安装. 但是如果处于公司内网时是无法连网安装的,下面就手动安装进行说明: 1.h ...
- 手写网站服务器~用Python手动实现一个简单的服务器,不借助任何框架在浏览器中输出任意内容
写在前面的一些P话: 在公司网站开发中,我们往往借助于Flask.Django等网站开发框架去提高网站开发效率.那么在面试后端开发工程师的时候,面试官可能就会问到网站开发的底层原理是什么? 我们不止仅 ...
- [Leetcode][Python]23: Merge k Sorted Lists
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 23: Merge k Sorted Listshttps://oj.leet ...
随机推荐
- 执行Sqlserver中waitfor delay延时操作或waitfor time定时操作
private static string connectionString = RBAC.Dal.DataRootBase.ConnectionString; private SqlConnecti ...
- PE格式第六讲,导出表
PE格式第六讲,导出表 请注意,下方字数比较多,其实结构挺简单,但是你如果把博客内容弄明白了,对你受益匪浅,千万不要看到字数多就懵了,其实字数多代表它重要.特别是第五步, 各种表中之间的关系. 作者: ...
- Ubuntu安装Jupyter Notebook
一.Jupyter介绍 Jupyter Notebook是一个交互式笔记本,支持运行40多种编程语言.Jupyter Notebook 的本质是一个 Web 应用程序,便于创建和共享文学化程序文档,支 ...
- Druid连接池
Druid 连接池简介 Druid首先是一个数据库连接池.Druid是目前最好的数据库连接池,在功能.性能.扩展性方面,都超过其他数据库连接池,包括DBCP.C3P0.BoneCP.Proxool.J ...
- Centos 7.3 安装配置 PostgreSQL 9.x
一.安装 PostgresSQL Centos 7 自带的 PostgresSQL 是 9.2 版的.因为,yum 已经做了国内源,速度飞快,所以直接就用 yum 安装了.依次执行以下命令即可,非常简 ...
- Windows下Mysql常用操作命令
以下命令中的服务启动及停止需要使用以管理员身份运行cmd.exe. 1.启动Mysql服务:net start [mysql服务名].示例: net start mysql57 结果: 2.停止Mys ...
- 容器与Docker简介(三)Docker相关术语——微软微服务电子书翻译系列
本节列出了在更加深入Docker之前应该熟悉的术语和定义. 有关详细的定义,请参阅Docker提供的术语表. 容器镜像(Container image):具有创建容器所需要的所有依赖和信息的包. 镜像 ...
- 聊聊Java中的反射(一)
本文为作者原创,转载请注明出处(http://www.cnblogs.com/mar-q/)by 负赑屃 反射reflection主要为了动态操作Java代码,它的主要功能体现在Java提供的refl ...
- 解决 iframe 在 ios 上不能滚动的问题
HTML代码在使用IFRAME或者其他HTML元素时,你需要使用一个元素(如DIV)来包装他们: <div class="scroll-wrapper"> <i ...
- hdu 3091 Necklace(状态压缩类似于TSP问题)
Necklace Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 327680/327680 K (Java/Others)Total ...