K-Means聚类算法的python实现

1.数据格式

Id(索引)R(特征)F(特征)M(特征)
1276232.61
2351507.11
3416817.62
4311232.81
51471913.05
6196220.07
752615.83
82621059.66
............

2.代码

(1)主体(输出聚类中心)

import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_excel("consumption_data.xls")
scaler = StandardScaler()
df_scaled = scaler.fit_transform(df.drop('Id', axis=1))
model = KMeans(n_clusters=3)
model.fit(df_scaled)

centers = pd.DataFrame(model.cluster_centers_, columns=df.drop('Id', axis=1).columns)
r1 = pd.Series(model.labels_).value_counts()
r = pd.concat([centers, r1], axis=1)
r.columns = list(df.drop('Id', axis=1).columns) + ['聚类类别数量']
print(r)

(2)可视化(聚类中心雷达图)

attributes = ['R', 'F', 'M']
angles = np.linspace(0, 2 * np.pi, len(attributes), endpoint=False).tolist()
angles += angles[:1]
fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True))
for i in range(len(centers)):
    values = centers.iloc[i].values.tolist()
    values += values[:1]
    ax.plot(angles, values, linewidth=1, linestyle='solid', label='Cluster {}'.format(i))
ax.set_xticks(angles[:-1])
ax.set_xticklabels(attributes)
ax.legend(loc='upper right', bbox_to_anchor=(1.1, 1.0))
plt.show()

3.后续更新中 

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值