In [ ]:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
In [ ]:
#define data
data= np.array([[1, 2], [1.5, 1.8], [5,8], [8,8], [1,0.6], [9, 11],
[8,2],[10,2], [9,3]])
In [ ]:
#visualize the data points
plt.figure(figsize=(5,5))
plt.scatter(data[:,0], data[:,1], s=100, color='goldenrod')
plt.show()
In [ ]:
# intialize centroids
centroids= np.random.randint(1, 11, size=(3,2))
colors= ['r', 'g', 'b']
print(centroids)
[[ 4 10] [ 2 2] [ 9 8]]
In [ ]:
#visualize the data as well as the centroids
plt.figure(figsize=(5,5))
for i in range(3):
plt.scatter(centroids[i,0], centroids[i,1], color=colors[i], s=200, marker='x', linewidth=3)
plt.scatter(data[:,0], data[:,1], s=100, color='goldenrod')
#plt.scatter(centroids[:,0], centroids[:,1], marker='*', s=200, color=colors)
plt.show()
In [ ]:
#apply k-means
kmeans= KMeans(n_clusters=3)
kmeans.fit(data)
Out[ ]:
KMeans(n_clusters=3)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
KMeans(n_clusters=3)
In [ ]:
#get the cluster centroids and labels
new_centroids= kmeans.cluster_centers_
labels= kmeans.labels_
print(new_centroids)
[[7.33333333 9. ] [1.16666667 1.46666667] [9. 2.33333333]]
In [ ]:
plt.figure(figsize=(5,5))
for i in range(len(data)):
plt.scatter(data[i][0], data[i][1], color=colors[labels[i]], s=100)
for i in range(3):
plt.scatter(new_centroids[i,0], new_centroids[i,1], s=200, marker='x', linewidths=3, c=colors[i])
plt.show()
In [ ]:
df= pd.read_csv('customer_cluster.csv')
df.head()
Out[ ]:
| Spending_Score | Visit_Frequency | |
|---|---|---|
| 0 | 26 | 4 |
| 1 | 27 | 5 |
| 2 | 34 | 4 |
| 3 | 33 | 4 |
| 4 | 30 | 4 |
In [ ]:
# apply k-means
kmeans= KMeans(n_clusters=3, random_state=42)
df['cluster']= kmeans.fit_predict(df)
df.head()
Out[ ]:
| Spending_Score | Visit_Frequency | cluster | |
|---|---|---|---|
| 0 | 26 | 4 | 2 |
| 1 | 27 | 5 | 2 |
| 2 | 34 | 4 | 2 |
| 3 | 33 | 4 | 2 |
| 4 | 30 | 4 | 2 |
In [ ]:
#visualize everything
sns.scatterplot(data=df, x='Visit_Frequency', y='Spending_Score', hue='cluster',
s=200, marker='h', palette={1:'orange', 0:'orchid', 2:'olive'})
plt.show()
In [ ]: