KMeans算法实践

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
font = {'family':'SimHei', 'size':'20'}
plt.rc('font', **font)
df = pd.read_csv('data.csv')
df.head()
CustomerIDGenderAgeAnnual Income (k$)Spending Score (1-100)
01Male191539
12Male211581
23Female20166
34Female231677
45Female311740
df.columns
Index(['CustomerID', 'Gender', 'Age', 'Annual Income (k$)',
       'Spending Score (1-100)'],
      dtype='object')
df.columns = ['用户ID', '性别', '年龄', '年收入', '支出']
df.head()
用户ID性别年龄年收入支出
01Male191539
12Male211581
23Female20166
34Female231677
45Female311740
df.isnull().sum()
用户ID    0
性别      0
年龄      0
年收入     0
支出      0
dtype: int64
df.describe()
用户ID年龄年收入支出
count200.000000200.000000200.000000200.000000
mean100.50000038.85000060.56000050.200000
std57.87918513.96900726.26472125.823522
min1.00000018.00000015.0000001.000000
25%50.75000028.75000041.50000034.750000
50%100.50000036.00000061.50000050.000000
75%150.25000049.00000078.00000073.000000
max200.00000070.000000137.00000099.000000
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 200 entries, 0 to 199
Data columns (total 5 columns):
用户ID    200 non-null int64
性别      200 non-null object
年龄      200 non-null int64
年收入     200 non-null int64
支出      200 non-null int64
dtypes: int64(4), object(1)
memory usage: 7.9+ KB

查看数据分布

fig = plt.figure(figsize=(20,8))
fig.suptitle('各指标数据分布')

# 第一个子图
ax1 = fig.add_subplot(221)
# 查看年龄分布
ax1.hist(df['年龄'])
ax1.title.set_text('年龄分布')

# 第二个子图
ax2 = fig.add_subplot(222)
# 查看性别比例
male, female = (df['性别'] == 'Male').sum(), (df['性别'] == 'Female').sum()
height = [male, female]
x = range(len(['男', '女']))
ax2.set_xticks(x)
ax2.set_xticklabels(['男', '女'])
ax2.bar(x, height=height)  # 这里要用数字类型[0,1]代替字符串类型['男', '女']。具体改动包括第15-17行代码
ax2.title.set_text('性别比例')

# 第三个子图
ax3 = fig.add_subplot(223)
# 查看年收入
ax3.hist(df['年收入'])
ax3.title.set_text('年收入')

#  第四个子图
ax1 = fig.add_subplot(224)
# 查看支出分布
ax1.hist(df['支出'])
ax1.title.set_text('支出')


fig.subplots_adjust(wspace=0.3,hspace=0.5)
plt.show()

output_9_0

年龄与年收入之间的关系

plt.figure(figsize=(12,6))
for gender in ['Male', 'Female']:
    plt.scatter(x='年龄',y='年收入'
                ,data=df[df['性别']==gender]
                ,s=200,alpha=0.5,label=gender)
plt.xlabel('年龄')
plt.ylabel('年收入')
plt.title('年龄与年收入之间的关系')
plt.legend()
plt.show()

output_11_0

年龄与支出之间的关系

plt.figure(figsize=(12,6))
for gender in ['Male','Female']:
    plt.scatter(x='年龄',y='支出'
                ,data=df[df['性别']==gender]
                ,s=200,alpha=0.5,label=gender)
plt.xlabel('年龄')
plt.ylabel('支出')
plt.title('年龄与支出之间的关系')
plt.legend()
plt.show()

output_13_0

年收入与支出之间的关系

plt.figure(figsize=(12,6))
for gender in ['Male','Female']:
    plt.scatter(x='年收入',y='支出'
                ,data=df[df['性别']==gender]
                ,s=200,alpha=0.5,label=gender)
plt.xlabel('年收入')
plt.ylabel('支出')
plt.title('年收入与支出之间的关系')
plt.legend()
plt.show()

output_15_0

年龄与支出的kmeans聚类分析

# 寻找最佳k值
x1 = df[['年龄', '支出']]
inertia = []
for i in range(1,11):
    km = KMeans(n_clusters=i)
    km.fit(x1)
    inertia.append(km.inertia_)   #  簇内误差平方和
plt.figure(1,figsize=(12,6))
plt.plot(range(1,11), inertia)
plt.title('查看最佳k值',fontsize=20)
plt.xlabel('簇的数量')
plt.ylabel('簇内误差平方和')
plt.show()

output_17_0

## 经过上图的观察,我们把k值取为4
km = KMeans(n_clusters=4)
y_means = km.fit_predict(x1)

plt.figure(figsize=(12,6))
plt.scatter(x1[y_means==0]['年龄'], x1[y_means==0]['支出'], s= 200,c='salmon')
plt.scatter(x1.iloc[y_means==1,0], x1.iloc[y_means==1,1], s= 200,c='yellowgreen')
plt.scatter(x1.iloc[y_means==2,0], x1.iloc[y_means==2,1], s= 200,c='cornflowerblue')
plt.scatter(x1.iloc[y_means==3,0], x1.iloc[y_means==3,1], s= 200,c='magenta')
plt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1],s=100,c='black',label='中心点')

plt.ylabel('支出')
plt.xlabel('年龄')
plt.legend()
plt.show()

output_18_0

年收入与支出的kmeans聚类分析

x2 = df[['年收入','支出']].values

inertia = []
for i in range(1,11):
    km = KMeans(n_clusters=i)
    km.fit(x2)
    inertia.append(km.inertia_) # 簇内误差平方和
plt.figure(figsize=(12,6))
plt.plot(range(1,11), inertia)
plt.title('查看最佳k值',fontsize=20)
plt.xlabel('簇的数量')
plt.ylabel('簇内误差平方和')
plt.show()

output_20_0

## 经过上图的观察,我们把k值取为5
km = KMeans(n_clusters=5)
y_means = km.fit_predict(x2)

plt.figure(figsize=(12,6))
plt.scatter(x2[y_means==0,0], x2[y_means==0,1], s= 200,c='salmon')
plt.scatter(x2[y_means==1,0], x2[y_means==1,1], s= 200,c='yellowgreen')
plt.scatter(x2[y_means==2,0], x2[y_means==2,1], s= 200,c='cornflowerblue')
plt.scatter(x2[y_means==3,0], x2[y_means==3,1], s= 200,c='magenta')
plt.scatter(x2[y_means==4,0], x2[y_means==4,1], s= 200,c='LightSeaGreen')
plt.scatter(km.cluster_centers_[:,0],km.cluster_centers_[:,1],s=100,c='black',label='中心点')

plt.ylabel('支出')
plt.xlabel('年收入')
plt.legend()
plt.show()
<matplotlib.figure.Figure at 0x1556354e2b0>
<matplotlib.figure.Figure at 0x155614b37f0>

output_21_2----------------------------------------------END-------------------------------------

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值