K-means算法怎么在python中使用

发布时间:2021-02-09 12:17:34

来源:亿速云

阅读:68

作者:Leah

本篇文章为大家展示了K-means算法怎么在python中使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

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)

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()

上述内容就是K-means算法怎么在python中使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

k-means算法python_K-means算法怎么在python中使用相关推荐

  1. k近邻回归算法python_K近邻算法用作回归的使用介绍(使用Python代码)

    介绍 在我遇到的所有机器学习算法中,KNN是最容易上手的.尽管它很简单,但事实上它其实在某些任务中非常有效(正如你将在本文中看到的那样). 甚至它可以做的更好?它可以用于分类和回归问题!然而,它其实更 ...

  2. 人工蜂群算法python_改进的人工蜂群算法解决聚类问题(在Python中的分步实现)...

    在 之前的文章 中,我介绍了如何通过实施名为Artificial Bee Colony(ABC)的群集智能(SI)算法来解决现实世界中的优化问题. 现在是时候让我们掌握一些真实的数据并解释我们如何使用 ...

  3. k近邻回归算法python_K-近邻回归算法的实用介绍(附Python代码)

    介绍 在我所遇到的所有机器学习算法中,KNN很容易被选择.尽管它很简单,但它在某些任务上被证明是非常有效的(如本文中所见). 甚至更好?它可以用于分类和回归问题!然而,它更广泛地用于分类问题.我很少看 ...

  4. 独家 | 基于TextRank算法的文本摘要(附Python代码)

    作者:Prateek Joshi 翻译:王威力 校对:丁楠雅 本文约3300字,建议阅读10分钟. 本文介绍TextRank算法及其在多篇单领域文本数据中抽取句子组成摘要中的应用. TextRank ...

  5. k均值聚类算法python_K均值和其他聚类算法:Python快速入门

    k均值聚类算法python This post was originally published here 这篇文章最初发表在这里 Clustering is the grouping of obje ...

  6. 介绍一下K近邻(KNN)算法,KNeighbors和RadiusNeighbors的差异是什么?各有什么优势?

    介绍一下K近邻(KNN)算法,KNeighbors和RadiusNeighbors的差异是什么?各有什么优势? K近邻(KNN)算法 近邻(Nearest Neighbor)算法既可以用于监督学习(分 ...

  7. K近邻(KNN)算法是基于实例的算法,如果训练样本数量庞大,预测的时候挨个计算距离效率会很低下,如何破解?

    K近邻(KNN)算法是基于实例的算法,如果训练样本数量庞大,预测的时候挨个计算距离效率会很低下,如何破解? K近邻(KNN)是最简单的算法之一,它计算预测样本与训练数据集中每个数据点之间的距离,并找到 ...

  8. Kmeans++、Mini-Batch Kmeans、Bisecting Kmeans、K中心点(K-Medoids)算法、K众数聚类、核K均值聚类

    Kmeans++.Mini-Batch Kmeans.Bisecting Kmeans.K中心点(K-Medoids)算法.K众数聚类.核K均值聚类 目录 Kmeans++.Mini-Batch Km ...

  9. 【算法】快速选择算法 ( 数组中找第 K 大元素 )

    算法 系列博客 [算法]刷题范围建议 和 代码规范 [算法]复杂度理论 ( 时间复杂度 ) [字符串]最长回文子串 ( 蛮力算法 ) [字符串]最长回文子串 ( 中心线枚举算法 ) [字符串]最长回文 ...

  10. C语言二叉树总和等于k的所有路径的算法(附完整源码)

    C语言二叉树总和等于k的所有路径的算法 C语言二叉树总和等于k的所有路径的算法完整源码(定义,实现,main函数测试) C语言二叉树总和等于k的所有路径的算法完整源码(定义,实现,main函数测试) ...

最新文章

  1. java 75-76
  2. 【OpenCV】8邻域种子填充法剔除短连通域的高效算法
  3. MySQL now()函数
  4. python函数注解
  5. eclipse.ini 修改默认编码为 UTF-8
  6. 360 支持linux版本下载地址,360安全浏览器国产稳定版本发布,提供deb软件包下载,附介绍...
  7. NOIP2016愤怒的小鸟 题解报告 【状压DP】
  8. 《Android 第1行代码》读后感—第11章【Android 特色开发——基于位置的服务】
  9. 一个例子搞懂Nacos服务发现
  10. linux下查看文件inode,Linux下如何寻找相同文件?
  11. Python爬取百度图片(高清原图)
  12. 祭奠自己逝去的三年时光
  13. 我的朋友老曹,居然用数据工具搞了这么多事
  14. 远程网络监视(rmon)与简单网络管理协议(snmp)之间是什么关系
  15. wordpress 数据库_在WordPress中使用数据库
  16. DataGrip离线安装数据库驱动
  17. 【ppp概念股龙头】PPP项目落地显著加速 四大板块牛股或受益
  18. warning: statement has no effect [-Wunused-value]
  19. 输出二叉树中从每个叶子结点到根结点的路径,统计二叉树的度为1的结点个数,二叉树算表达式(C语言)
  20. 11.9-11.13宁阳东平五日

热门文章

  1. Emacs 主题设置
  2. 从程序员到架构师需要掌握哪些技能
  3. Wincc中,如何利用C脚本对变量进行置位+复位+取反操作?
  4. PlayMaker — 动作
  5. 一看书就瞌睡,在学习编程中会遇见的一些问题
  6. nullptr VS NULL
  7. 云服务器部署springboot项目
  8. EPSON-300K+打印机
  9. plsql远程oracle 乱码,oracle11g_64位连接32位PLSQL中文乱码
  10. 音频知识点(3)- Speex 简介