-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmeans_clusterization.py
40 lines (31 loc) · 1.02 KB
/
kmeans_clusterization.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
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
def show_clusters(data, columns, n_centroids=2):
extracted_data = data[columns].to_numpy()
km = KMeans(n_clusters=n_centroids)
y_km = km.fit_predict(extracted_data)
colors = ['lightgreen', 'orange', 'lightblue', 'red']
markers = ['s', 'o', 'v', '.']
# Plot all clusters
for i in range(n_centroids):
plt.scatter(
extracted_data[y_km == i, 0], extracted_data[y_km == i, 1],
s=50, c=colors[i],
marker=markers[i], edgecolor='black',
label=f"cluster {i + 1}"
)
# Plot centroids
plt.scatter(
km.cluster_centers_[:, 0], km.cluster_centers_[:, 1],
s=250, marker='*',
c='red', edgecolor='black',
label='centroids'
)
plt.legend(scatterpoints=1)
plt.grid()
plt.xlabel(columns[0])
plt.ylabel(columns[1])
plt.show()
df = pd.read_csv('cars.csv')
show_clusters(df, ['cubicinches', 'weightlbs'], n_centroids=4)