3 机器学习之聚类

news2024/10/6 6:45:21

学习笔记自,慕课网 《Python3 入门人工智能》
https://coding.imooc.com/lesson/418.html#mid=32716
分类问题

1. 无监督学习

机器学习的一种方法,没有给定事先标记过的训练示例,自动对输入的数据进行分类或分群

优点:
1)算法不受监督信息的约束,可能考虑到新的信息
2)不需要标签数据,极大程度扩大数据样本

主要应用:聚类分析、关联规则、维度缩减
在这里插入图片描述
在这里插入图片描述
聚类分析,又称为群分析,根据对象某些属性的相似度,将其自动化分为不同的类别
在这里插入图片描述

2. KMeans、KNN、Mean-shift

2.1 KMeans

Kmeans聚类:以空间中k个点为中心进行聚类,对最靠近他们的对象归类,是聚类算法中最为基础但也最为重要的算法。
在这里插入图片描述
在这里插入图片描述

2.2 KMeans算法流程

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

a) k == 2 分两类,随机选取聚类中心
b) 计算每个点都选取的聚类中心的距离
c d) 根据距离就划分好了两个类别,左上的红色部分离聚类中心红色近,右下的蓝色部分离聚类蓝色中心近
e) 更新聚类中心,并重新计算每个点到新的聚类中心的距离依此划分新的聚类
f) 直到中心点不再变化为止

2.3 KNN – 监督学习

K近邻分类模型,给定一个训练数据集,对新的输入实例,在训练数据集中找到与该实例最邻近的K个实例,这K个实例的多数属于某个类,就是把该输入实例分类到这个类中
在这里插入图片描述

2.4 均值漂移聚类

在这里插入图片描述
均值不断移动
在这里插入图片描述

3. 实战准备

任务:
1、采用Kmeans算法实现2D数据自动聚类,预测V1=80,V2=60数据类别;
2、计算预测准确率,完成结果矫正
3、采用KNN、Meanshift算法,重复步骤1-2
数据:data.csv

''' 
任务:
1、**采用Kmeans算法实现2D数据自动聚类,预测V1=80,V2=60数据类别**;
2、计算预测准确率,完成结果矫正
3、采用KNN、Meanshift算法,重复步骤1-2
数据:data.csv
''' 
#load the data
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans

data = pd.read_csv('data.csv')
data.head()
#define X and y
X = data.drop(['labels'],axis=1)
y = data.loc[:,'labels']
y.head()
pd.value_counts(y)
# %matplotlib inline
fig1 = plt.figure()
plt.scatter(X.loc[:,'V1'],X.loc[:,'V2'])
plt.title("un-labled data")
plt.xlabel('V1')
plt.ylabel('V2')
plt.show()
fig1 = plt.figure()
label0 = plt.scatter(X.loc[:,'V1'][y==0],X.loc[:,'V2'][y==0])
label1 = plt.scatter(X.loc[:,'V1'][y==1],X.loc[:,'V2'][y==1])
label2 = plt.scatter(X.loc[:,'V1'][y==2],X.loc[:,'V2'][y==2])

plt.title("labled data")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.show()
#print(X.shape,y.shape)
# 1.KMeans
KM = KMeans(n_clusters=3,random_state=0)
KM.fit(X)
# 获取模型确定的中心点
centers = KM.cluster_centers_
fig3 = plt.figure()
label0 = plt.scatter(X.loc[:,'V1'][y==0],X.loc[:,'V2'][y==0])
label1 = plt.scatter(X.loc[:,'V1'][y==1],X.loc[:,'V2'][y==1])
label2 = plt.scatter(X.loc[:,'V1'][y==2],X.loc[:,'V2'][y==2])

plt.title("labled data")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.scatter(centers[:,0],centers[:,1])
plt.show()
y_predict_test = KM.predict([[80,60]])
#print(y_predict_test)
y_predict = KM.predict(X)
#print(pd.value_counts(y_predict),pd.value_counts(y))
# 准确率计算
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y,y_predict)
print("accuracy", accuracy)
#visualize the data and results
fig4 = plt.subplot(121)
label0 = plt.scatter(X.loc[:,'V1'][y_predict==0],X.loc[:,'V2'][y_predict==0])
label1 = plt.scatter(X.loc[:,'V1'][y_predict==1],X.loc[:,'V2'][y_predict==1])
label2 = plt.scatter(X.loc[:,'V1'][y_predict==2],X.loc[:,'V2'][y_predict==2])

plt.title("predicted data")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.scatter(centers[:,0],centers[:,1])

fig5 = plt.subplot(122)
label0 = plt.scatter(X.loc[:,'V1'][y==0],X.loc[:,'V2'][y==0])
label1 = plt.scatter(X.loc[:,'V1'][y==1],X.loc[:,'V2'][y==1])
label2 = plt.scatter(X.loc[:,'V1'][y==2],X.loc[:,'V2'][y==2])

plt.title("labled data")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.scatter(centers[:,0],centers[:,1])
plt.show()
# 预测结果矫正
y_corrected = []
for i in y_predict:
    if i==0:
        y_corrected.append(1)
    elif i==1:
        y_corrected.append(2)
    else:
        y_corrected.append(0)
print(pd.value_counts(y_corrected),pd.value_counts(y))
print(accuracy_score(y,y_corrected))
y_corrected = np.array(y_corrected)
print(type(y_corrected))
fig6 = plt.subplot(121)
label0 = plt.scatter(X.loc[:,'V1'][y_corrected==0],X.loc[:,'V2'][y_corrected==0])
label1 = plt.scatter(X.loc[:,'V1'][y_corrected==1],X.loc[:,'V2'][y_corrected==1])
label2 = plt.scatter(X.loc[:,'V1'][y_corrected==2],X.loc[:,'V2'][y_corrected==2])

plt.title("corrected data")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.scatter(centers[:,0],centers[:,1])

fig7 = plt.subplot(122)
label0 = plt.scatter(X.loc[:,'V1'][y==0],X.loc[:,'V2'][y==0])
label1 = plt.scatter(X.loc[:,'V1'][y==1],X.loc[:,'V2'][y==1])
label2 = plt.scatter(X.loc[:,'V1'][y==2],X.loc[:,'V2'][y==2])

plt.title("labled data")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.scatter(centers[:,0],centers[:,1])
plt.show()
# 3.establish a KNN model
from sklearn.neighbors import KNeighborsClassifier
KNN = KNeighborsClassifier(n_neighbors=3)
KNN.fit(X,y)
#predict based on the test data V1=80, V2=60
y_predict_knn_test = KNN.predict([[80,60]])
y_predict_knn = KNN.predict(X)
print(y_predict_knn_test)
print('knn accuracy:',accuracy_score(y,y_predict_knn))
print(pd.value_counts(y_predict_knn),pd.value_counts(y))
fig6 = plt.subplot(121)
label0 = plt.scatter(X.loc[:,'V1'][y_predict_knn==0],X.loc[:,'V2'][y_predict_knn==0])
label1 = plt.scatter(X.loc[:,'V1'][y_predict_knn==1],X.loc[:,'V2'][y_predict_knn==1])
label2 = plt.scatter(X.loc[:,'V1'][y_predict_knn==2],X.loc[:,'V2'][y_predict_knn==2])

plt.title("knn results")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.scatter(centers[:,0],centers[:,1])

fig7 = plt.subplot(122)
label0 = plt.scatter(X.loc[:,'V1'][y==0],X.loc[:,'V2'][y==0])
label1 = plt.scatter(X.loc[:,'V1'][y==1],X.loc[:,'V2'][y==1])
label2 = plt.scatter(X.loc[:,'V1'][y==2],X.loc[:,'V2'][y==2])

plt.title("labled data")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.scatter(centers[:,0],centers[:,1])
plt.show()
from sklearn.cluster import MeanShift,estimate_bandwidth
#obtain the bandwidth 区域半径
bw = estimate_bandwidth(X,n_samples=500)
#print(bw)
# 3.establish the meanshift model-un-supervised model
ms = MeanShift(bandwidth=bw)
ms.fit(X)
y_predict_ms = ms.predict(X)
print(pd.value_counts(y_predict_ms),pd.value_counts(y))
print(centers)#kmeans聚类中心
#新增代码 打印使用meanshift算法获取的聚类中心 与kmeans算法对比 中心点非常接近
centers2 = ms.cluster_centers_
print(centers2)#meanshift聚类中心
fig6 = plt.subplot(121)
label0 = plt.scatter(X.loc[:,'V1'][y_predict_ms==0],X.loc[:,'V2'][y_predict_ms==0])
label1 = plt.scatter(X.loc[:,'V1'][y_predict_ms==1],X.loc[:,'V2'][y_predict_ms==1])
label2 = plt.scatter(X.loc[:,'V1'][y_predict_ms==2],X.loc[:,'V2'][y_predict_ms==2])

plt.title("ms results")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.scatter(centers[:,0],centers[:,1])

fig7 = plt.subplot(122)
label0 = plt.scatter(X.loc[:,'V1'][y==0],X.loc[:,'V2'][y==0])
label1 = plt.scatter(X.loc[:,'V1'][y==1],X.loc[:,'V2'][y==1])
label2 = plt.scatter(X.loc[:,'V1'][y==2],X.loc[:,'V2'][y==2])

plt.title("labled data")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.scatter(centers[:,0],centers[:,1])
plt.show()

#correct the results
y_corrected_ms = []
for i in y_predict_ms:
    if i==0:
        y_corrected_ms.append(2)
    elif i==1:
        y_corrected_ms.append(1)
    else:
        y_corrected_ms.append(0)
print(pd.value_counts(y_corrected_ms),pd.value_counts(y))

#convert the results to numpy array
y_corrected_ms = np.array(y_corrected_ms)
print(type(y_corrected_ms))
fig6 = plt.subplot(121)
label0 = plt.scatter(X.loc[:,'V1'][y_corrected_ms==0],X.loc[:,'V2'][y_corrected_ms==0])
label1 = plt.scatter(X.loc[:,'V1'][y_corrected_ms==1],X.loc[:,'V2'][y_corrected_ms==1])
label2 = plt.scatter(X.loc[:,'V1'][y_corrected_ms==2],X.loc[:,'V2'][y_corrected_ms==2])

plt.title("ms corrected results")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.scatter(centers[:,0],centers[:,1])

fig7 = plt.subplot(122)
label0 = plt.scatter(X.loc[:,'V1'][y==0],X.loc[:,'V2'][y==0])
label1 = plt.scatter(X.loc[:,'V1'][y==1],X.loc[:,'V2'][y==1])
label2 = plt.scatter(X.loc[:,'V1'][y==2],X.loc[:,'V2'][y==2])

plt.title("labled data")
plt.xlabel('V1')
plt.ylabel('V2')
plt.legend((label0,label1,label2),('label0','label1','label2'))
plt.scatter(centers[:,0],centers[:,1])
plt.show()

在这里插入图片描述
[80,60] result[2] label2
在实际中分类后需要矫正数据,如上代码有矫正数据的过程。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/148483.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

今年十八,喜欢CTF-杂项

目录 前言 菜狗杯杂项签到 我吐了你随意 损坏的压缩包 misc4 misc5 前言 🍀作者简介:被吉师散养、喜欢前端、学过后端、练过CTF、玩过DOS、不喜欢java的不知名学生。 🍁个人主页:被吉师散养的职业混子 🫒每日emo&am…

Rad Studio 11.2 安装 QuickBurro 7.21 中间件组件教程

背景 QuickBurro 官方网址:http://www.quickburro.org/ 系统环境:Rad Studio 11.2 安装其他的组件操作和这个一样的,同样可以参考 开始配置 先打开 Rad Studio 11,依次点击 File–Open Project… 然后找到你解压的 qbcn 目录下的…

React 环境搭建以及创建项目工程(二)

创建工程 首先创建一个工程 npx create-react-app weibo cd移动到当前创建的文件下 cd weibo 安装 React 路由 npm install react-router react-router-dom5.2.0 --save 安装 npm install 安依赖包 npm install antd --save npm install axios --save 安装less和less-…

PyCharm安装步骤

以64位的Windows10系统为例: 下载链接:Thank you for downloading PyCharm! 下载并打开安装包 在 Installation Options(安装选项)页面按下图所示勾选相应内容: 等待电脑自动安装完成 在PyCharm里编写程序 第1步&a…

【python】天平最少砝码设计

题目 有一架天平,砝码的种类和个数要你来设计。给定一个整数n,则待称重的物品的重量可能是 [1,n] 之间的整数,砝码可以放在左盘也可以放在右盘,要能称出所有 [1,n] 重量的物品,请问如何设计砝码的种类和个数&#xff…

Unreal UFUNCTION函数宏标记

BlueprintCallable,使C中的函数在蓝图中能被调用,新建C类CustomActor继承AActor,并分别声明public、protected、private方法:拖拽一个CustomActor到Map中,打开关卡蓝图,可以到无法在蓝图中调出C中的方法:我们为这三个方法添加BlueprintCallable标记:然后在蓝图中调用:可以发现,…

驱动程序开发:多点电容触摸屏

驱动程序开发:多点电容触摸屏一、编写驱动前的知识准备1、CST340触摸屏芯片寄存器2、CST340触摸屏的硬件原理图3、电容触摸屏驱动是由几种linux驱动框架组成的4、linux多点电容触摸的(Multi-touch,简称 MT)协议二、驱动程序的编写1、修改设备树2、驱动程…

Spring AOP【AOP的基本实现与动态代理JDK Proxy 和 CGLIB区别】

Spring AOP【AOP的基本实现与动态代理JDK Proxy 和 CGLIB区别】🍎一. Spring AOP🍒1.1 什么是Spring AOP🍒1.2 Spring AOP的作用🍒1.3 AOP的组成🍉1.3.1 切面(Aspect)🍉1.3.2 连接点…

大数据NiFi(十一):NiFi入门案例一

文章目录 NiFi入门案例一 一、配置“GetFile”处理器

Elastic-Job分布式任务调度

一.什么是任务调度 **任务调度:**是指系统为了自动完成特点任务,在约定的特定时刻去执行任务的过程。有了任务调度就不需要人力去实现,系统可以在某个时间自动执行任务。 二,任务调度的实现方式: 1.**多线程方式实现…

【博客579】netfilter network flow 和 routing decision的网络流处理交互关系

netfilter网络流转(network flow)与路由决策(routing decision)的网络流处理交互关系 1、场景: 我们可以通过iptables来基于netfilter机制下发我们的hook处理函数,那么我们平时iptables的四表五链与报文的…

JDBC简介

大家好,今天给大家分享jdbc 首先我们要知道什么是jdbc JDBC(Java DataBase Connectivity) :Java数据库连接技术:具体讲就是通过Java连接广泛的数据库,并对表中数据执行增、删、改、查等操作的技术 看它的架构图 或者看这个图…

flowable工作流架构分析

flowable工作流目录概述需求:设计思路实现思路分析1.复杂的状态的或者状态的维度增加的状的条件极为复杂2.工作流3.BPMN2.0协议4.协议的元素5.互斥网关包容性网关(Inclusive Gateway)参考资料和推荐阅读Survive by day and develop by night.…

车载以太网 - DoIP诊断消息处理逻辑 - 05

前面我们已经介绍了DoIP信息头部处理逻辑和路由激活处理,那根据DoIP报文的顺序,在路由激活处理完成后,接下来我们就需要发送真正的DoIP诊断信息了,那今天我们就来介绍下DoIP诊断消息的处理逻辑。 诊断消息处理逻辑 DoIP诊断报文结构: 上面表格对于DoIP诊断报文的…

Android 11 SystemUI(状态/导航栏)-图标按键的深浅色

概述 自 Android 5.0 版本,Android 带来了沉浸式系统 bar(状态栏和导航栏),Android 的视觉效果进一步提高,各大 app 厂商也在大多数场景上使用沉浸式效果。6.0开始提供了View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR标志位&a…

MVC架构模式 | 使用银行转账的功能实现引出MVC架构模式

一、银行转账的功能实现数据库表的准备创建数据库表&#xff0c;主要包括三个字段&#xff1a;自增的id、账户名、账户余额不使用MVC架构模式完成账户转账首先写一个页面&#xff0c;写入转账的账户和金额&#xff1b;并发送post请求<% page contentType"text/html;cha…

【JavaEE】进入Web开发的世界-HTML

目录 一、HTML 1.1概念篇 1.2工具篇 1.2.1文本类型的标签 1.2.2多媒体标签 1.2.3超链接 1.2.4target 1.2.5表格相关的标签 1.2.6 列表标签 1.2.7表单标签 进入Web开发的世界&#xff0c;了解html、css、JavaScript的使用。 Web开发的核心&#xff1a;准备各式各样的资…

元壤:国内首家免费的数字藏品、DAO数字化营销SaaS平台

元壤&#xff1a;国内首家免费的数字藏品、DAO数字化营销SaaS平台 元壤是 Web3.0 时代 NFT 数字藏品与用户服务的数字化工具。元壤是中国企业数字资产化及数字藏品营销解决方案提供商。元壤致力于通过产品和服务,助力企业资产数字化,数字营销化,通过科技驱动数字商业变革,让数…

如何仿真MOS电容的电压-电容曲线?

一、原理 电容的阻抗为&#xff1a; 假设在电容两端施加频率为 f 的小信号电压 v &#xff0c;电容上流过的小信号电流为 i &#xff0c;那么三者有如下关系&#xff1a; 二、仿真 设置频率为1/2pi&#xff0c;这样算出来斜率即为1/C。设置f为0.159155 斜率就是1/C&#xff0c…

你问我答|DDR5对企业用户意味着什么?

自从2014年DDR4内存在市场推出以来,时间已经过去了八年,这对日新月异的计算机行业来说,无疑是相当长的一段时间了。这期间,更快的CPU和存储介质等产品的技术进步,促进了对更大容量的内存、更高内存带宽和更快速率的需求,服务器市场尤其如此。      而在2023年,我们终于迎来…