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 ...
随机推荐
- css3制作网页中常见的小箭头
/* css3三角形(向上 ▲) */ div.arrow-up { width:0px; height:0px; border-left:5px solid transparent; /* 右透明 ...
- 标准模型和IE模型的区别:
标准模型和IE模型的区别: 标准盒子模型的content的宽高不包含其他部分,但是IE盒子模型的content部分包含padding和border 比如:margin=10:border=5:p ...
- Bash : test 命令
在 Bash 脚本中我们一般会使用 test 命令来进行条件检查.test 命令的返回值为 0 或 1.0 表示 true, 1 表示 false.简单起见,我们可以直接认为 test 的结果为 tr ...
- 数据库中有的字段为null时,反馈到页面上是什么也不显示?如何用一个【无】字来代替呢?
<asp:ListView ID="listViewCustomer" DataSourceID="ods_Customer" runat="s ...
- string使用
一.list和string转化 List转字符串,用逗号隔开 List<string> list = new List<string>();list.Add("a&q ...
- win10 3dmax 激活后反复激活和激活码无效问题
我也是遇到这个问题在网上找答案,像什么断网,清理注册表,删除某个.dat文件 各种试了好多都没管用 弄这个弄了五六个小时才总算成功 心累 现在我总结一下这些方法 我是第一条成功的 其他的我试着都没用 ...
- win10 uwp clone
clone 可以用MemberwiseClone来复制一个类 但这个复制是浅复制,创建一个新的object然后复制值字段,对于引用就直接复制引用,不复制引用的本身,指向同样引用 如果要复制引用,可以使 ...
- C# 动态加载卸载 DLL
我最近做的软件,需要检测dll或exe是否混淆,需要反射获得类名,这时发现,C#可以加载DLL,但不能卸载DLL.于是在网上找到一个方法,可以动态加载DLL,不使用时可以卸载. 我在写一个WPF 程序 ...
- Spring 为Bean对象执行初始化和销毁方法
1)初始化: ①可以利用<bean>元素的init-method="方法名"属性指定初始化方法. ②指定的初始化方法是在构造方法调用后自动执行.若非单例模式,则每创建一 ...
- CRUSH: Controlled, Scalable, Decentralized Placement of Replicated Data译文
原文地址:http://www.oschina.net/translate/crush-controlled-scalable-decentralized-placement-of-replicate ...