Cluster Analysis in Python
Shaumik Daityari
Business Analyst
kmeans(obs, k_or_guess, iter, thresh, check_finite)
obs
: standardized observationsk_or_guess
: number of clustersiter
: number of iterations (default: 20)thres
: threshold (default: 1e-05)check_finite
: whether to check if observations contain only finite numbers (default: True)Returns two objects: cluster centers, distortion
vq(obs, code_book, check_finite=True)
obs
: standardized observationscode_book
: cluster centerscheck_finite
: whether to check if observations contain only finite numbers (default: True)Returns two objects: a list of cluster labels, a list of distortions
kmeans
returns a single value of distortionsvq
returns a list of distortions.# Import kmeans and vq functions
from scipy.cluster.vq import kmeans, vq
# Generate cluster centers and labels
cluster_centers, _ = kmeans(df[['scaled_x', 'scaled_y']], 3)
df['cluster_labels'], _ = vq(df[['scaled_x', 'scaled_y']], cluster_centers)
# Plot clusters
sns.scatterplot(x='scaled_x', y='scaled_y', hue='cluster_labels', data=df)
plt.show()
Cluster Analysis in Python