K_means聚类python实战

K_means工作原理

step1:随机选择K个点作为类(簇)的中心点,K为重要的超参数,选择k值可用手肘法;
step2:将每个点分配到最近的类中心点,并重新计算每个类的中心点;
step3:重复step2,直到类中心不发生变化,或者迭代次数到了你设置的值。

K_means调用sklearn工具来实现

step1:导入数据;
step2:数据预处理;
step3:手肘法选用k值;
step4:聚类结果输入,最后再人工判断每个簇的特性。

import pandas as pd
from sklearn.cluster import KMeans
import warnings
warnings.filterwarnings('ignore')

#step1导入数据, CustomerID为客户ID,Gender为性别,Age为年龄,Annual Income (k$)为客户收入,Spending Score (1-100)为客户消费
data = pd.read_csv('Mall_Customers.csv')
feature = ['Gender','Age','Annual Income (k$)','Spending Score (1-100)']
train_data = data[feature]
#print(train_data)

#step2.数据预处理,字符型变量(gender)转为0,1,归一化
from sklearn.preprocessing import LabelEncoder,MinMaxScaler
LE = LabelEncoder()
train_data['Gender'] = LE.fit_transform(train_data['Gender'])
MMS = MinMaxScaler()
train_data = MMS.fit_transform(train_data)
train_data = pd.DataFrame(train_data,columns = feature)
#print(train_data)

#step3.手肘法选择k值
SSE =[]
for i in range(1,10):
    model = KMeans(n_clusters=i)
    model.fit(train_data)
    pred = model.predict(train_data)
    SSE.append(model.inertia_)
import matplotlib.pyplot as plt
#显示中文
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.plot(range(1,10),SSE)
plt.xlabel('簇数量——聚类的k值')
plt.ylabel('簇的误差平方和SSE')
plt.show()

#step4.选择斜率最大的,SSE下降梯度最大的值,k = 2进行聚类(选3、4也可)
data['category'] = KMeans(n_clusters=2).fit_predict(train_data)
data.to_csv('Mall_Customers_category.csv',index = False)

你可能感兴趣的:(统计学,python,python,聚类)