首先从sklearn里面载入iris数据集

如下所示

Sepal_Length  Sepal_Width  Petal_Length  Petal_Width  Species
0             5.1          3.5           1.4          0.2        0
1             4.9          3.0           1.4          0.2        0
2             4.7          3.2           1.3          0.2        0
3             4.6          3.1           1.5          0.2        0
4             5.0          3.6           1.4          0.2        0
..            ...          ...           ...          ...      ...
145           6.7          3.0           5.2          2.3        2
146           6.3          2.5           5.0          1.9        2
147           6.5          3.0           5.2          2.0        2
148           6.2          3.4           5.4          2.3        2
149           5.9          3.0           5.1          1.8        2

[150 rows x 5 columns]

可以看到有4列为特征,最后一列为类别

这里为了画图方便仅使用了Sepal_Length  和Petal_Width  两列

可以看到特征和结果相关性挺高的

假如没有标签,看起来可以用kmeans解决,最后用kmeans看能不能得到类似的一个结果

# -*- coding: utf-8 -*-
import glob
from collections import defaultdict
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
import pandas as pd
import numpy as npdef plot_scatter(df, name, centers=None, title=None):'''画图'''plt.figure()plt.scatter(df['Sepal_Length'], df['Petal_Width'], c=df['Species'])plt.xlabel('Sepal_Length')plt.ylabel('Petal_Width')plt.legend()if centers:plt.scatter([i[0] for i in centers], [i[1] for i in centers], c='r')if title:plt.title(title)plt.savefig(name)def distance(point_a, point_b):'''欧氏距离计算'''return np.sqrt(sum((np.array(point_a) - np.array(point_b)) ** 2))def k_means(points, k):centers = [points[i] for i in range(k)]dict_ = []iter_num = 0while True:point_dict = defaultdict(list)for point in points:distances = [distance(center, point) for center in centers]class_ = np.argmin(distances)dict_.append({'Sepal_Length': point[0], 'Petal_Width': point[1], 'Species': class_}, )point_dict[class_].append(point)print({k: len(v) for k, v in point_dict.items()})new_centers = [np.array(points).mean(axis=0) for class_, points in point_dict.items()]dis = (np.array(new_centers) - centers)if abs(dis.mean()) <= 0.0002:breakelse:centers = new_centersplot_scatter(pd.DataFrame(dict_), f'kmeans_{iter_num}.png', centers, iter_num)iter_num += 1def png2jif():'''迭代生成的png转为动图'''file_names = glob.glob('*.png')from PIL import Imageim = Image.open(file_names[0])images = []for file_name in file_names[1:]:images.append(Image.open(file_name))im.save('gif.gif', save_all=True, append_images=images, loop=1, duration=500, comment=b"aaabb")def get_iris_df():iris = load_iris()iris_d = pd.DataFrame(iris['data'], columns=['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width'])iris_d['Species'] = iris.targetiris_d.dropna(inplace=True)return iris_dif __name__ == '__main__':iris_df = get_iris_df()plot_scatter(iris_df, 'raw.png')print(iris_df)points = iris_df[['Sepal_Length', 'Petal_Width']].valuesk = 3k_means(points, k)png2jif()

红色为中心点,可以看到通过kmeans可以得到一个和原始结果相近的一个结果

kmeans算法python实现(iris数据集)相关推荐

  1. 2021-03-15 数据挖掘算法—K-Means算法 Python版本

    数据挖掘算法-K-Means算法 Python版本 简介 又叫K-均值算法,是非监督学习中的聚类算法. 基本思想 k-means算法比较简单.在k-means算法中,用cluster来表示簇:容易证明 ...

  2. ML之KMeans:利用KMeans算法对Boston房价数据集(两特征+归一化)进行二聚类分析

    ML之KMeans:利用KMeans算法对Boston房价数据集(两特征+归一化)进行二聚类分析 目录 利用KMeans算法对Boston房价数据集(两特征+归一化)进行二聚类分析 设计思路 输出结果 ...

  3. 【KNN】使用KNN算法实现对iris数据集的分类

    ** 一.实验报告 ** 1. 实验目的:使用KNN算法实现对iris数据集的分类 2. 实验要求:(1)5次随机选取,对比分类准确率(2)探讨不同k值对分类准确率的影响 二.实验内容 1. 数据预处 ...

  4. python计算iris数据集的均值_K均值(K-Means)

    聚类是数据挖掘中的基本任务,聚类是将大量数据集中具有"相似"特征的数据点划分为统一类别,并最终生成多个类的方法. 聚类分析的基本思想是"物以类聚.人以群分",因 ...

  5. python计算iris数据集的均值_模糊C均值聚类算法及python实现

    目录 本文采用数据集为iris,将iris.txt放在程序的同一文件夹下.请先自行下载好. 模糊理论 模糊控制是自动化控制领域的一项经典方法.其原理则是模糊数学.模糊逻辑.1965,L. A. Zad ...

  6. 【机器学习算法】手动Python实现KNN分类算法,并用iris数据集检验模型效果

    目录 一.KNN算法Python实现 1.导入包 2. 画图,展示不同电影在图上的分布 3.训练样本和待测样本准备 4.计算待测样本点到每个训练样本点的距离 5.查找离待测样本点最近的K个训练样本点的 ...

  7. 基于flink使用K-Means算法对KDD CUP99数据集进行聚类分析

    1.算法简介 kmeans算法又称k均值算法,是一种聚类算法,属于无监督学习算法. 对于给定的样本集,kmeans将其中相似的样本成员分类组织到一起,最终将样本集划分成K个簇,每个簇内的样本成员相似度 ...

  8. Python机器学习iris数据集预处理和模型训练

    机器学习模型训练 一.iris数据集简介 二.基本数据操作和模型训练 一.iris数据集简介 iris数据集的中文名是安德森鸢尾花卉数据集,英文全称是Anderson`s Iris data set. ...

  9. FCM聚类算法详解(Python实现iris数据集)

    参考:https://blog.csdn.net/on2way/article/details/47087201 模糊C均值(Fuzzy C-means)算法简称FCM算法,是一种基于目标函数的模糊聚 ...

  10. 数据挖掘-聚类分析(Python实现K-Means算法)

    概念: 聚类分析(cluster analysis ):是一组将研究对象分为相对同质的群组(clusters)的统计分析技术.聚类分析也叫分类分析,或者数值分类.聚类的输入是一组未被标记的样本,聚类根 ...

最新文章

  1. 网络方法的发展及最新iDIRECT方法介绍
  2. R语言str_starts函数和str_ends函数检查在字符串的开头或者结尾是否存在特定字符串或者字符串模式
  3. linux下ftp服务器的搭建与使用
  4. jsp uri=http://java.sun.com/jsp/jstl/core报错解决
  5. flutter图片点击跳转_使用Flutter之后,我们的CPU占用率降了50%
  6. excel实战应用案例100讲(十)-下载的文件显示“文件已损坏,无法打开”?
  7. 华为彭松:基于C.A.F模型构建联接竞争力,创造新增长
  8. c++ auto用法_不想写表达式的类型?试试auto吧
  9. iVMS-4200 Vs区别_杏林早报 | 西芹、水芹、旱芹...功效有区别,吃对才真降血压!...
  10. TensorFlow机器学习实战指南之第二章
  11. php redis 事务应用,redis事务有什么用
  12. 《python深度学习》总结与感想
  13. android rtmp 播放器下载,android rtmp player 除了播放一般的视频格式 - 下载 - 搜珍网...
  14. 九个完全免费的PPT模板网站
  15. doors需求管理导入HTML,Telelogic Doors 需求管理工具使用手记
  16. 华为mate30怎么更换鸿蒙系统,怎么升级到鸿蒙2.0系统呀
  17. SpringBoot整合Redis实现优惠券秒杀服务(笔记+优化思路版)
  18. 论文浅尝 | MISC:融合COMET的混合策略模型进行情感支持对话
  19. 电源上的sense什么意思_开关电源基本术语
  20. centos下如何查看磁盘使用情况命令

热门文章

  1. 基于Mac制作iPhone铃声教程,iTunes定制铃声
  2. multisim中pwl_(Multisim电子电路仿真教程)第3章Multisim仿真元件库与虚拟仪器.ppt
  3. 数据库可视化软件:Navicat系列
  4. sap abap开发从入门到精通_ABAP关键字 IS BOUND, IS NOT INITIAL和IS ASSIGNED的用法辨析
  5. [前端]使用meta控制双核浏览器默认使用webkit/chrome内核
  6. sitemesh学习
  7. 兄弟9055cdn硒鼓清零_兄弟打印机清零设置
  8. Python爬虫采集网易云音乐热评实战
  9. ubuntu如何查看java版本_Ubuntu 如何查看安装的 JDK
  10. 饥荒指令代码大全一览