当前位置: 首页 > news >正文

[机器学习]基于K-means聚类算法的鸢尾花数据及分类

基于Kmeans,对鸢尾花数据集前两个特征进行聚类分析

  • 通过迭代优化,将150个样本划分到K个簇中。

  • 目标函数:最小化所有样本到其所属簇中心的距离平方和。

  • 算法步骤:

    1. 随机初始化K个簇中心。

    2. 将每个样本分配到最近的中心。

    3. 计算均值确定每个簇的中心(均值)。

    4. 重复第2和3步直到稳定收敛。

程序代码:

import mathimport numpy as np
from matplotlib import pyplot as plt
from sklearn import datasetsplt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = Falsedata = datasets.load_iris().data
labels = datasets.load_iris().target
print('数据维度',data.shape)
features = data[:,: 2]
print('特征',features)num_clusters = 6
epoch = 150
J_sum = []def J_calculate(features,divide_re,center):J = 0for s1 in range(150):distances = ((features[s1][0]-center[divide_re[s1]][0]) ** 2) + ((features[s1][1]-center[divide_re[s1]][1]) ** 2)#print(distances)J = J + distancesreturn Jdef decision(features,divide_re,center,epoch):J_best = []for _ in range(epoch):J_b = math.inffor s1 in range(150):best = Nonemin_J_now = math.inffor s2 in range(len(center)):divide_re[s1] = s2J_now = J_calculate(features,divide_re,center)if J_now < min_J_now:min_J_now = J_nowbest = s2divide_re[s1] = bestfor i in range(len(center)):xc = []yc = []for j in range(150):if (divide_re[j] == i):xc.append(features[j][0])yc.append(features[j][1])center[i] = [np.mean(xc), np.mean(yc)]if(min_J_now<J_b):J_b = min_J_nowJ_best.append(J_b)return features,divide_re,center,J_bestfor i in range(2,num_clusters+1):print(f'\n分{i}类:\n')center = features[np.random.choice(features.shape[0], i, replace=False)]print("初始中心点", center)distances = np.linalg.norm(features[:, np.newaxis, :] - center, axis=2)divide = np.argmin(distances,axis=1)divide_re = []for x in range(150):divide_re.append(divide[x])print("初始样本分类", divide_re)features,divide_re,center,J_best = decision(features,divide_re,center,epoch)print(f'{i}类最佳J值为:',J_best[epoch-1])J_sum.append(J_best[epoch-1])plt.scatter(features[:, 0], features[:, 1], c=divide_re, cmap='viridis', edgecolors='k')plt.scatter(center[:, 0], center[:, 1], marker='x', s=30, linewidths=3, color='red')plt.title(f'{i}类C均值分类法结果')plt.xlabel('第一特征')plt.ylabel('第二特征')plt.show()
plt.figure()
plt.plot(range(2, num_clusters + 1), J_sum, marker='o')
plt.title('J与类别数量关系曲线')
plt.xlabel('类别数量')
plt.ylabel('J_sum 值')
plt.show()

运行结果:

数据维度 (150, 4)
特征 [[5.1 3.5]
[4.9 3. ]
[4.7 3.2]
[4.6 3.1]
[5.  3.6]
[5.4 3.9]
[4.6 3.4]
[5.  3.4]
[4.4 2.9]
[4.9 3.1]
[5.4 3.7]
[4.8 3.4]
[4.8 3. ]
[4.3 3. ]
[5.8 4. ]
[5.7 4.4]
[5.4 3.9]
[5.1 3.5]
[5.7 3.8]
[5.1 3.8]
[5.4 3.4]
[5.1 3.7]
[4.6 3.6]
[5.1 3.3]
[4.8 3.4]
[5.  3. ]
[5.  3.4]
[5.2 3.5]
[5.2 3.4]
[4.7 3.2]
[4.8 3.1]
[5.4 3.4]
[5.2 4.1]
[5.5 4.2]
[4.9 3.1]
[5.  3.2]
[5.5 3.5]
[4.9 3.6]
[4.4 3. ]
[5.1 3.4]
[5.  3.5]
[4.5 2.3]
[4.4 3.2]
[5.  3.5]
[5.1 3.8]
[4.8 3. ]
[5.1 3.8]
[4.6 3.2]
[5.3 3.7]
[5.  3.3]
[7.  3.2]
[6.4 3.2]
[6.9 3.1]
[5.5 2.3]
[6.5 2.8]
[5.7 2.8]
[6.3 3.3]
[4.9 2.4]
[6.6 2.9]
[5.2 2.7]
[5.  2. ]
[5.9 3. ]
[6.  2.2]
[6.1 2.9]
[5.6 2.9]
[6.7 3.1]
[5.6 3. ]
[5.8 2.7]
[6.2 2.2]
[5.6 2.5]
[5.9 3.2]
[6.1 2.8]
[6.3 2.5]
[6.1 2.8]
[6.4 2.9]
[6.6 3. ]
[6.8 2.8]
[6.7 3. ]
[6.  2.9]
[5.7 2.6]
[5.5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1, 1, 5, 5, 1, 5, 4, 4, 0, 0, 5, 1, 1, 1, 1, 1, 1, 3, 4, 1, 5, 1, 1, 5, 1, 1, 1, 5, 1, 5, 1, 1, 3, 1, 0, 5, 4, 0, 2, 0, 0, 4, 4, 0, 0, 1, 1, 4, 4, 0, 0, 1, 0, 1, 0, 5, 4, 0, 5, 5, 0, 0, 0, 0, 0, 5, 1, 0, 3, 4, 5, 0, 4, 0, 1, 4, 4, 0, 1, 4, 3, 5]
6类最佳J值为: 18.150987445152886

进程已结束,退出代码0

http://www.dtcms.com/a/356376.html

相关文章:

  • 把 AI 塞进「智能跳绳」——基于 MEMS 传感器的零样本卡路里估算器
  • 机器学习回顾——线性回归
  • GitHub 宕机自救指南:打造韧性开发体系
  • 基于站点、模式、遥感多源降水数据融合与评估;Python驱动下,从基础处理、机器学习建模到气候态产品生成的全流程解析
  • Consul 操作命令汇总 - Prometheus服务注册
  • 选华为实验工具:eNSP Pro 和社区在线实验哪个更适合?
  • 腾讯位置商业授权微信小程序距离计算
  • OpenAI GPT-realtime 实时语音 API 完整指南:2025年语音AI的革命性突破
  • STM32的RTC模块及其应用场景
  • MTK Linux DRM分析(二十三)- MTK mtk_drm_crtc.c(Part2)
  • 嵌入式Linux驱动开发 - GPIO LED驱动
  • 税务岗位能力提升培训课程推荐
  • 嵌入式Linux驱动开发:定时器驱动
  • 解析DB-GPT项目中三个 get_all_model_instances 方法的区别
  • 【WebRTC】从入门到忘记
  • 解密 Vue 3 shallowRef:浅层响应式 vs 深度响应式的性能对决
  • 园区智慧水电管理系统:让能源管理从“成本黑洞”变“利润引擎”
  • 【GM3568JHF】FPGA+ARM异构开发板 使用指南:以太网
  • nginx 怎么将 https 请求转为 http
  • AR巡检系统:数字化传统工作流程SOP的第一步
  • //Q是一个队列,S是一个空栈,实现将队列中的元素逆置的算法。
  • 从零开始学习单片机17
  • 医疗AI时代的生物医学Go编程:高性能计算与精准医疗的案例分析(五)
  • AR智能眼镜:能源行业运维的数字化革新
  • iOS 文件管理与 uni-app 性能优化实战 多工具协作的完整指南
  • Frida-dexdump 使用指南:从内存中脱取安卓 Dex 文件
  • Go对接全球期货数据源指南:基于StockTV API实现多品种实时监控
  • LeetCode第二题知识点2 ---- 栈、堆、地址
  • 不止 ChatGPT:多模态 AI(文本 + 图像 + 音频)正重构内容创作全流程
  • 数据质检之springboot通过yarn调用spark作业实现数据质量检测