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:
  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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.