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的Flask框架中的signals信号机制
Jun 13 Python
python获取当前运行函数名称的方法实例代码
Apr 06 Python
Python轻量级ORM框架Peewee访问sqlite数据库的方法详解
Jul 20 Python
python pandas中DataFrame类型数据操作函数的方法
Apr 08 Python
浅谈dataframe中更改列属性的方法
Jul 10 Python
Python lambda表达式用法实例分析
Dec 25 Python
python使用KNN算法识别手写数字
Apr 25 Python
简单了解python中的f.b.u.r函数
Nov 02 Python
Python3的socket使用方法详解
Feb 18 Python
Python3自定义http/https请求拦截mitmproxy脚本实例
May 11 Python
如何验证python安装成功
Jul 06 Python
python 获取域名到期时间的方法步骤
Feb 10 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
Ajax+PHP快速上手及简单应用说明
2013/07/24 PHP
PHP中的use关键字概述
2014/07/23 PHP
php简单备份与还原MySql的方法
2016/05/09 PHP
laravel ORM关联关系中的 with和whereHas用法
2019/10/16 PHP
jquery中获取元素的几种方式小结
2011/07/05 Javascript
jquery插件珍藏(图片局部放大/信息提示框)
2013/01/08 Javascript
javascript检测页面是否缩放的小例子
2013/05/16 Javascript
浅析Node.js的Stream模块中的Readable对象
2015/07/29 Javascript
基于Bootstrap和jQuery构建前端分页工具实例代码
2016/11/23 Javascript
Javascript之面向对象--封装
2016/12/02 Javascript
浅谈jQuery的bind和unbind事件(绑定和解绑事件)
2017/03/02 Javascript
js 数字、字符串、布尔值的转换方法(必看)
2017/04/07 Javascript
深入理解Nodejs Global 模块
2017/06/03 NodeJs
node.js中axios使用心得总结
2017/11/29 Javascript
vue.js编译时给生成的文件增加版本号
2018/09/17 Javascript
使用angular-cli webpack创建多个包的方法
2018/10/16 Javascript
关于vue的npm run dev和npm run build的区别介绍
2019/01/14 Javascript
layui实现根据table数据判断按钮显示情况的方法
2019/09/26 Javascript
JS面向对象实现飞机大战
2020/08/26 Javascript
tensorflow 1.0用CNN进行图像分类
2018/04/15 Python
Python3数字求和的实例
2019/02/19 Python
使用python实现抓取腾讯视频所有电影的爬虫
2019/04/15 Python
Python自动化之数据驱动让你的脚本简洁10倍【推荐】
2019/06/04 Python
Python实现简单的列表冒泡排序和反转列表操作示例
2019/07/10 Python
python实现爬虫抓取小说功能示例【抓取金庸小说】
2019/08/09 Python
python 画函数曲线示例
2019/12/04 Python
Python 微信公众号文章爬取的示例代码
2020/11/30 Python
复古服装:RetroStage
2019/05/10 全球购物
牵手50香港:专为黄金岁月的单身人士而设的交友网站
2020/08/14 全球购物
可贵的沉默教学反思
2014/02/06 职场文书
环保建议书100字
2014/05/14 职场文书
项目负责人任命书
2014/06/04 职场文书
在职员工证明书
2014/09/19 职场文书
应届毕业生求职信范文
2015/03/19 职场文书
2015社区六五普法工作总结
2015/04/21 职场文书
Nginx使用X-Accel-Redirect实现静态文件下载的统计、鉴权、防盗链、限速等
2021/04/04 Servers