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制作最美应用的爬虫
Oct 28 Python
Python简单实现子网掩码转换的方法
Apr 13 Python
一篇文章读懂Python赋值与拷贝
Apr 19 Python
python3通过selenium爬虫获取到dj商品的实例代码
Apr 25 Python
pandas.DataFrame的pivot()和unstack()实现行转列
Jul 06 Python
使用Python调取任意数字资产钱包余额功能
Aug 15 Python
python GUI库图形界面开发之PyQt5打印控件QPrinter详细使用方法与实例
Feb 28 Python
python 操作mysql数据中fetchone()和fetchall()方式
May 15 Python
Python程序慢的重要原因
Sep 04 Python
Python-openpyxl表格读取写入的案例详解
Nov 02 Python
如何在scrapy中集成selenium爬取网页的方法
Nov 18 Python
pytorch 如何使用float64训练
May 24 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开发文件系统实例讲解
2006/10/09 PHP
图书管理程序(二)
2006/10/09 PHP
解决dede生成静态页和动态页转换的一些问题,及火车采集入库生成动态的办法
2007/03/29 PHP
PHP网站基础优化方法小结
2008/09/29 PHP
php和jquery实现地图区域数据统计展示数据示例
2014/02/12 PHP
ThinkPHP函数详解之M方法和R方法
2015/09/10 PHP
PHP 常用时间函数资料整理
2016/10/22 PHP
PHP远程连接oracle数据库操作实现方法图文详解
2019/04/11 PHP
收藏Javascript中常用的55个经典技巧
2007/08/12 Javascript
JS 日期验证正则附asp日期格式化函数
2009/09/11 Javascript
Jquery带搜索框的下拉菜单
2013/05/06 Javascript
jquery 添加节点的几种方法介绍
2013/09/04 Javascript
js中call与apply的用法小结
2013/12/28 Javascript
JS生成不重复随机数组的函数代码
2014/06/10 Javascript
jQuery中detach()方法用法实例
2014/12/25 Javascript
javascript中利用柯里化函数实现bind方法【推荐】
2016/04/29 Javascript
怎么引入(调用)一个JS文件
2016/05/26 Javascript
Bootstrap 3.x打印预览背景色与文字显示异常的解决
2016/11/06 Javascript
深入理解vue路由的使用
2017/03/24 Javascript
bootstrap模态框嵌套、tabindex属性、去除阴影的示例代码
2017/10/17 Javascript
解决微信小程序中的滚动穿透问题
2019/09/16 Javascript
详解vue中使用transition和animation的实例代码
2020/12/12 Vue.js
[03:49]辉夜杯现场龙骑士COSER秀情商“我喜欢芬队!”
2015/12/27 DOTA
python将unicode转为str的方法
2017/06/21 Python
pandas 数据实现行间计算的方法
2018/06/08 Python
python 安装教程之Pycharm安装及配置字体主题,换行,自动更新
2020/03/13 Python
详解Css3新特性应用之过渡与动画
2017/01/10 HTML / CSS
美国生鲜及杂货电商:FreshDirect
2018/01/29 全球购物
英国探险旅游专家:Explore
2018/12/20 全球购物
草莓网官网:StrawberryNET
2019/08/21 全球购物
汽车机修工岗位职责
2014/03/06 职场文书
高中生第一学年自我鉴定
2014/09/12 职场文书
个人工作总结范文2014
2014/11/07 职场文书
社团个人总结范文
2015/03/05 职场文书
学校证明范文
2015/06/24 职场文书
解决MultipartFile.transferTo(dest) 报FileNotFoundExcep的问题
2021/07/01 Java/Android