-
Notifications
You must be signed in to change notification settings - Fork 0
/
k_means_clustering_amazon_user_segmentation.py
60 lines (42 loc) · 1.62 KB
/
k_means_clustering_amazon_user_segmentation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# -*- coding: utf-8 -*-
"""K_Means_Clustering_AMAZON-User-Segmentation.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Vp2byU7cctf5p2fk24byleymIokgMq_M
# K Means Clustering
## Importing libraries
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
"""## Importing dataset"""
dataset = pd.read_csv('Amazon.com Clusturing Model.csv')
X = dataset.iloc[:, [2, 4]].values
print(X)
"""## Optimal number of clusters via Elbow Method"""
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
kmeans = KMeans(n_clusters= i, init= 'k-means++', random_state = 21)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
plt.plot(range(1,11), wcss)
plt.title('WCSS via Elbow method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS Value')
plt.show()
"""## K Means Model Training on Training set"""
kmeans = KMeans(n_clusters = 4, init = 'k-means++', random_state = 42)
y_means = kmeans.fit_predict(X)
print(y_means)
"""## Visualizing Clusters"""
plt.scatter(X[y_means == 0, 0], X[y_means == 0, 1], s = 100, c = 'magenta', label = 'Cluster 1')
plt.scatter(X[y_means == 1, 0], X[y_means == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')
plt.scatter(X[y_means == 2, 0], X[y_means == 2, 1], s = 100, c = 'red', label = 'Cluster 3')
plt.scatter(X[y_means == 3, 0], X[y_means == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'black', label = 'Centroids')
plt.title('Cluster of Amazon users')
plt.xlabel('Age')
plt.ylabel('Purchase Rating')
plt.legend()
plt.show()