K-means聚类算法的可视化
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 08:45:31 2023
@author: ZLM
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["axes.unicode_minus"]=False
df=pd.read_excel('聚类数据data.xlsx',sheet_name='Sheet1')
x=df['x']
y=df['y']
df=df.values
plt.figure(dpi=200)
plt.scatter(x, y)
#假设聚为2类,初始化聚类中心
# x=np.random.rand(2,1)*5
# y=np.random.rand(2,1)*5
plt.scatter(x[0], y[0],marker='o',s=100)
plt.scatter(x[1], y[1],marker='o',s=100)
#计算数据集中,每条数据到初始聚类中心的距离,并将其分配到距离较小的那个聚类中心
labels1=[0,2]
labels2=list(set(range(20))-set(labels1))
x1=x[labels1]
y1=y[labels1]
x2=x[labels2]
y2=y[labels2]
#更新聚类中心
plt.figure(dpi=200)
plt.scatter(x, y)
plt.scatter(np.mean(x1), np.mean(y1),marker='o',s=100)
plt.scatter(np.mean(x2), np.mean(y2),marker='o',s=100)
#再次更新聚类中心
labels1=list(range(8))
labels2=list(set(range(20))-set(labels1))
x1=x[labels1]
y1=y[labels1]
x2=x[labels2]
y2=y[labels2]
plt.figure(dpi=200)
plt.scatter(x, y)
plt.scatter(np.mean(x1), np.mean(y1),marker='o',s=100)
plt.scatter(np.mean(x2), np.mean(y2),marker='o',s=100)
#调用sklearn中的KMeans类
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=2,n_init=10)
kmeans.fit(df)
labels=kmeans.labels_
centers=kmeans.cluster_centers_
plt.figure(dpi=200)
plt.scatter(x, y,c=labels)
plt.scatter(centers[0][0], centers[0][1],marker='o',s=100)
plt.scatter(centers[1][0], centers[1][1],marker='o',s=100)
#预测
results=kmeans.predict([[0, -1],[4,5], [12, 3]])