# kaggle | 商城客户细分数据

``````import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import os
print(os.listdir("../input"))
['Mall_Customers.csv']
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import warnings
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
warnings.filterwarnings('ignore')

``X=data.iloc[:,[3,4]].values # 将年度收入和支出分数作为特征``

``````from sklearn.cluster import KMeans
wcss=[]
for i in range(1,11):
kmeans=KMeans(n_clusters=i,init='k-means++',max_iter=300,n_init=10,random_state=0)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
plt.plot(range(1,11),wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()``````

``````kmeans=KMeans(n_clusters=5,init='k-means++',max_iter=300,n_init=10,random_state=0)
y_kmeans=kmeans.fit_predict(X)``````

``````plt.scatter(X[y_kmeans==0,0],X[y_kmeans==0,1],s=100,c='magenta',label='Careful')
plt.scatter(X[y_kmeans==1,0],X[y_kmeans==1,1],s=100,c='yellow',label='Standard')
plt.scatter(X[y_kmeans==2,0],X[y_kmeans==2,1],s=100,c='green',label='Target')
plt.scatter(X[y_kmeans==3,0],X[y_kmeans==3,1],s=100,c='cyan',label='Careless')
plt.scatter(X[y_kmeans==4,0],X[y_kmeans==4,1],s=100,c='burlywood',label='Sensible')
plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=300,c='red',label='Centroids')
plt.title('Cluster of Clients')
plt.xlabel('Annual Income (k\$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show``````

``````Cluster 1- High income low spending =Careful

Cluster 2- Medium income medium spending =Standard

Cluster 3- High Income and high spending =Target

Cluster 4- Low Income and high spending =Careless

Cluster 5- Low Income and low spending =Sensible``````

``````sns.lmplot(x='Age', y='Spending Score (1-100)', data=data,fit_reg=True,hue='Gender')
plt.show()``````

``````data.sort_values(['Age'])
plt.figure(figsize=(10,8))
plt.bar(data['Age'],data['Spending Score (1-100)'])
plt.xlabel('Age')
plt.ylabel('Spending Score')
plt.show()``````

``````label_encoder=LabelEncoder()
integer_encoded=label_encoder.fit_transform(data.iloc[:,1].values)
data['Gender']=integer_encoded

``````hm=sns.heatmap(data.iloc[:,1:5].corr(), annot = True, linewidths=.5, cmap='Blues')
hm.set_title(label='Heatmap of dataset', fontsize=20)
hm
plt.ioff()``````

``````dataset_1 = data.iloc[:,1:5]

``````results = []
for i in range(1,10):
kmeans = KMeans(n_clusters=i, init='k-means++')
res = kmeans.fit(dataset_1)
results.append(res.score(dataset_1))
plt.plot(range(1,10),results)
plt.xlabel('Num Clusters')
plt.ylabel('score')
plt.title('Elbow Curve')``````

``````dataset_2 = dataset[:,3:5]

``````results = []
for i in range(1,10):
kmeans = KMeans(n_clusters=i, init='k-means++')
res = kmeans.fit(dataset_2)
results.append(res.score(dataset_2))
plt.plot(range(1,10),results)
plt.xlabel('Num Clusters')
plt.ylabel('score')
plt.title('Elbow Curve')``````

https://www.kaggle.com/vjchoudhary7/customer-segmentation-tutorial-in-python