python中K-means算法基础知识点


Posted in Python onJanuary 25, 2021

能够学习和掌握编程,最好的学习方式,就是去掌握基本的使用技巧,再多的概念意义,总归都是为了使用服务的,K-means算法又叫K-均值算法,是非监督学习中的聚类算法。主要有三个元素,其中N是元素个数,x表示元素,c(j)表示第j簇的质心,下面就使用方式给大家简单介绍实例使用。

K-Means算法进行聚类分析

km = KMeans(n_clusters = 3)
km.fit(X)
centers = km.cluster_centers_
print(centers)

三个簇的中心点坐标为:

[[5.006 3.428 ]

[6.81276596 3.07446809]

[5.77358491 2.69245283]]

比较一下K-Means聚类结果和实际样本之间的差别:

predicted_labels = km.labels_
fig, axes = plt.subplots(1, 2, figsize=(16,8))
axes[0].scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Set1, 
        edgecolor='k', s=150)
axes[1].scatter(X[:, 0], X[:, 1], c=predicted_labels, cmap=plt.cm.Set1,
        edgecolor='k', s=150)
axes[0].set_xlabel('Sepal length', fontsize=16)
axes[0].set_ylabel('Sepal width', fontsize=16)
axes[1].set_xlabel('Sepal length', fontsize=16)
axes[1].set_ylabel('Sepal width', fontsize=16)
axes[0].tick_params(direction='in', length=10, width=5, colors='k', labelsize=20)
axes[1].tick_params(direction='in', length=10, width=5, colors='k', labelsize=20)
axes[0].set_title('Actual', fontsize=18)
axes[1].set_title('Predicted', fontsize=18)

k-means算法实例扩展内容:

# -*- coding: utf-8 -*- 
"""Excercise 9.4"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sys
import random

data = pd.read_csv(filepath_or_buffer = '../dataset/watermelon4.0.csv', sep = ',')[["密度","含糖率"]].values

########################################## K-means ####################################### 
k = int(sys.argv[1])
#Randomly choose k samples from data as mean vectors
mean_vectors = random.sample(data,k)

def dist(p1,p2):
 return np.sqrt(sum((p1-p2)*(p1-p2)))
while True:
 print mean_vectors
 clusters = map ((lambda x:[x]), mean_vectors) 
 for sample in data:
  distances = map((lambda m: dist(sample,m)), mean_vectors) 
  min_index = distances.index(min(distances))
  clusters[min_index].append(sample)
 new_mean_vectors = []
 for c,v in zip(clusters,mean_vectors):
  new_mean_vector = sum(c)/len(c)
  #If the difference betweenthe new mean vector and the old mean vector is less than 0.0001
  #then do not updata the mean vector
  if all(np.divide((new_mean_vector-v),v) < np.array([0.0001,0.0001]) ):
   new_mean_vectors.append(v) 
  else:
   new_mean_vectors.append(new_mean_vector) 
 if np.array_equal(mean_vectors,new_mean_vectors):
  break
 else:
  mean_vectors = new_mean_vectors 

#Show the clustering result
total_colors = ['r','y','g','b','c','m','k']
colors = random.sample(total_colors,k)
for cluster,color in zip(clusters,colors):
 density = map(lambda arr:arr[0],cluster)
 sugar_content = map(lambda arr:arr[1],cluster)
 plt.scatter(density,sugar_content,c = color)
plt.show()

到此这篇关于python中K-means算法基础知识点的文章就介绍到这了,更多相关python中K-means算法是什么内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python删除指定目录下过期文件的2个脚本分享
Apr 10 Python
django使用xlwt导出excel文件实例代码
Feb 06 Python
jupyter notebook引用from pyecharts.charts import Bar运行报错
Apr 23 Python
Jupyter中直接显示Matplotlib的图形方法
May 24 Python
python3+selenium实现qq邮箱登陆并发送邮件功能
Jan 23 Python
Django框架组成结构、基本概念与文件功能分析
Jul 30 Python
Python 70行代码实现简单算式计算器解析
Aug 30 Python
详解使用django-mama-cas快速搭建CAS服务的实现
Oct 30 Python
django框架ModelForm组件用法详解
Dec 11 Python
详解python中groupby函数通俗易懂
May 14 Python
Python dict的常用方法示例代码
Jun 23 Python
python 爬虫如何实现百度翻译
Nov 16 Python
python中HTMLParser模块知识点总结
Jan 25 #Python
pycharm配置QtDesigner的超详细方法
Jan 25 #Python
Python扫描端口的实现
Jan 25 #Python
Python 将代码转换为可执行文件脱离python环境运行(步骤详解)
Jan 25 #Python
Python实现京东抢秒杀功能
Jan 25 #Python
Python Process创建进程的2种方法详解
Jan 25 #Python
使用python对excel表格处理的一些小功能
Jan 25 #Python
You might like
php模板函数 正则实现代码
2012/10/15 PHP
PHP Hash算法:Times33算法代码实例
2015/05/13 PHP
javascript 限制输入和粘贴(IE,firefox测试通过)
2008/11/14 Javascript
jQuery 瀑布流 浮动布局(一)(延迟AJAX加载图片)
2012/05/23 Javascript
jquery实现手风琴效果实例代码
2013/11/15 Javascript
利用JQuery和Servlet实现跨域提交请求示例分享
2014/02/12 Javascript
node.js+Ajax实现获取HTTP服务器返回数据
2014/11/26 Javascript
使用jQuery实现星级评分代码分享
2014/12/09 Javascript
不使用ajax实现无刷新提交表单
2014/12/21 Javascript
jquery实现简易的移动端验证表单
2015/11/08 Javascript
jQuery无刷新上传之uploadify3.1简单使用
2016/06/18 Javascript
解决Vue.js父组件$on无法监听子组件$emit触发事件的问题
2018/09/12 Javascript
Vue-Cli 3.0 中配置高德地图的两种方式
2019/06/19 Javascript
js回调函数仿360开机
2019/12/26 Javascript
three.js欧拉角和四元数的使用方法
2020/07/26 Javascript
[01:20]DOTA2上海特级锦标赛现场采访:谁的ID最受青睐
2016/03/25 DOTA
Python3中常用的处理时间和实现定时任务的方法的介绍
2015/04/07 Python
python对指定目录下文件进行批量重命名的方法
2015/04/18 Python
Python的gevent框架的入门教程
2015/04/29 Python
pyqt5简介及安装方法介绍
2018/01/31 Python
Python 通配符删除文件的实例
2018/04/24 Python
selenium python 实现基本自动化测试的示例代码
2019/02/25 Python
Python3模拟curl发送post请求操作示例
2019/05/03 Python
Python实现通过解析域名获取ip地址的方法分析
2019/05/17 Python
用scikit-learn和pandas学习线性回归的方法
2019/06/21 Python
Python爬虫图片懒加载技术 selenium和PhantomJS解析
2019/09/18 Python
Python for i in range ()用法详解
2020/09/18 Python
pycharm设置当前工作目录的操作(working directory)
2020/02/14 Python
Python对wav文件的重采样实例
2020/02/25 Python
ANINE BING官方网站:奢华的衣橱基本款和时尚永恒的单品
2019/11/26 全球购物
专业幼师实习生自我鉴定范文
2013/12/08 职场文书
名人演讲稿范文
2013/12/28 职场文书
新学期校长寄语
2014/01/18 职场文书
实习单位鉴定意见
2015/06/04 职场文书
聘任书格式及范文
2015/09/21 职场文书
2022微信温控新功能上线
2022/05/09 数码科技