Implementing k-means with scikit-learn

Having developed our own k-means clustering model, we can now learn how to use scikit-learn for a quicker solution by performing the following steps:

  1. First, import the KMeans class and initialize a model with three clusters as follows:
>>> from sklearn.cluster import KMeans>>> kmeans_sk = KMeans(n_clusters=3, random_state=42)

The KMeans class takes in the following important parameters:

  1. We then fit the model on the data:
>>> kmeans_sk.fit(X)
  1. After that, we can obtain the clustering results, including the clusters for data samples and centroids of individual clusters:
>>> clusters_sk = kmeans_sk.labels_ ...

Get Python Machine Learning By Example - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.