python k-means代码实现,聚类分析代码实战
2023-09-27 14:20:36 时间
1.引入依赖
import numpy as np
import matplotlib.pyplot as plt
# 从sklearn中直接生成聚类数据
from sklearn.datasets.samples_generator import make_blobs
2.数据加载
x, y = make_blobs( n_samples=100, centers=6, random_state=1234, cluster_std=0.6 )
plt.figure(figsize=(6,6))
plt.scatter(x[:,0], x[:,1], c=y)
plt.show()
3.算法实现:这里大家注意cdist()的用法
# 引入scipy中的距离函数,默认欧式距离
from scipy.spatial.distance import cdist
class K_Means(object):
# 初始化,参数 n_clusters(K)、迭代次数max_iter、初始质心 centroids
def __init__(self, n_clusters=5, max_iter=300, centroids=[]):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.centroids = np.array( centroids, dtype=np.float )
# 训练模型方法,k-means聚类过程,传入原始数据
def fit(self, data):
# 假如没有指定初始质心,就随机选取data中的点作为初始质心
if( self.centroids.shape == (0,) ):
# 从data中随机生成0到data行数的6个整数,作为索引值
self.centroids = data[ np.random.randint( 0, data.shape[0], self.n_clusters ) ,: ]
# 开始迭代
for i in range(self.max_iter):
# 1. 计算距离矩阵,得到的是一个100*6的矩阵
distances = cdist(data, self.centroids)
# 2. 对距离按有近到远排序,选取最近的质心点的类别,作为当前点的分类
c_ind = np.argmin( distances, axis=1 )
# 3. 对每一类数据进行均值计算,更新质心点坐标
for i in range(self.n_clusters):
# 排除掉没有出现在c_ind里的类别
if i in c_ind:
# 选出所有类别是i的点,取data里面坐标的均值,更新第i个质心
self.centroids[i] = np.mean( data[c_ind==i], axis=0 )
# 实现预测方法
def predict(self, samples):
# 跟上面一样,先计算距离矩阵,然后选取距离最近的那个质心的类别
distances = cdist(samples, self.centroids)
c_ind = np.argmin( distances, axis=1 )
return c_ind
dist = np.array([[121,221,32,43],
[121,1,12,23],
[65,21,2,43],
[1,221,32,43],
[21,11,22,3],])
c_ind = np.argmin( dist, axis=1 )
print(c_ind)
x_new=x[0:5]
print(x_new)
print(c_ind==2)
print(x_new[c_ind==2])
np.mean(x_new[c_ind==2], axis=0)
4.测试绘图
# 定义一个绘制子图函数
def plotKMeans(x, y, centroids, subplot, title):
# 分配子图,121表示1行2列的子图中的第一个
plt.subplot(subplot)
plt.scatter(x[:,0], x[:,1], c='r')
# 画出质心点
plt.scatter(centroids[:,0], centroids[:,1], c=np.array(range(5)), s=100)
plt.title(title)
kmeans = K_Means(max_iter=300, centroids=np.array([[2,1],[2,2],[2,3],[2,4],[2,5]]))
plt.figure(figsize=(16, 6))
plotKMeans( x, y, kmeans.centroids, 121, 'Initial State' )
# 开始聚类
kmeans.fit(x)
plotKMeans( x, y, kmeans.centroids, 122, 'Final State' )
# 预测新数据点的类别
x_new = np.array([[0,0],[10,7]])
y_pred = kmeans.predict(x_new)
print('质心:',kmeans.centroids)
print('预测:',y_pred)
# plt.scatter(x_new[:,0], x_new[:,1], s=100, c='black')
5.结果如下:
左侧是自己定义的质心,右侧是聚类后的质心。
声明: 代码参考b站up主《尚硅谷》
相关文章
- python实现二分查找算法例子代码
- 利用简单的python机器学习库玩转『低代码』
- 【Python】秀儿!两行代码制作你的专属动态二维码
- 考虑梯水电站群的水火电节能调度(Python代码实现)
- 综合能源系统分析的统一能路理论(三):《稳态与动态潮流计算》(Python代码实现)
- 粒子群算法求解电力系统环境经济调度+微电网调度(风、光、电动车、柴油机、主网)(Python代码实现)
- 基于DistFlow的含分布式电源配电网优化模型【IEEE39节点】(Python代码实现)
- 微电网两阶段鲁棒优化经济调度方法(Python代码实现)
- 微电网重构|基于群稀疏性的机会约束微电网重构(Matlab代码和Python代码实现)
- 【负荷预测】基于灰色预测算法的负荷预测(Python代码实现)
- 【路径规划】基于A*算法和Dijkstra算法的路径规划(Python代码实现)
- 2020年高教社杯全国大学生数学建模竞赛---校园供水系统智能管理(Python代码实现)
- 2020年高教社杯全国大学生数学建模竞赛---校园供水系统智能管理(Python代码实现)
- 【数学建模】“华为杯”高级神经网络Keras(Python代码实现)
- 【数学建模】华为杯学习——特征选择(Python代码实现)
- 基于改进的离散PSO算法的FJSP的研究(Python代码实现)
- Python数据分析主要功能是什么?可以用来做什么?
- python 调用 C++ code
- ChatGPT 使用Python调用revChatGPT.V1代码
- 使用PyQt(Python+Qt)+动态编译36行代码实现的计算器
- python装饰器实现对异常代码出现进行监控
- Python 通过hdbcli配置连接SAP HANA数据库方法及示例代码
- python常用快捷键,写代码事半功倍
- 原来Python可以这么强大,只需要百行Python代码就能开发出游戏
- 42个Python实用小例子[内附200+代码地址]
- python实在太好用了,只需一行代码,就能实现文件共享服务器
- python - 30行代码实现微信机器人自动回复消息
- python - postgres数据库通过models创建表,直接上代码如下:
- python代码实现http get请求curl -u 用户名:密码 url -X get