Skip to Content
40 Algorithms Every Programmer Should Know
book

40 Algorithms Every Programmer Should Know

by Imran Ahmad
June 2020
Intermediate to advanced
382 pages
11h 39m
English
Packt Publishing
Content preview from 40 Algorithms Every Programmer Should Know

Coding the k-means algorithm

Let's look at how we can code the k-means algorithm in Python:

  1. First, let's import the packages that we will need to code for the k-means algorithm. Note that we are importing the sklearn package for k-means clustering:

from sklearn import clusterimport pandas as pdimport numpy as np
  1. To use k-means clustering, let's create 20 data points in a two-dimensional problem space that we will be using for k-means clustering:

dataset = pd.DataFrame({    'x': [11, 21, 28, 17, 29, 33, 24, 45, 45, 52, 51, 52, 55, 53, 55, 61, 62, 70, 72, 10],    'y': [39, 36, 30, 52, 53, 46, 55, 59, 63, 70, 66, 63, 58, 23, 14, 8, 18, 7, 24, 10]})
  1. Let's have two clusters (k = 2) and then create the cluster by calling the fit functions:

myKmeans ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

50 Algorithms Every Programmer Should Know - Second Edition

50 Algorithms Every Programmer Should Know - Second Edition

Imran Ahmad
Grokking Algorithms

Grokking Algorithms

Aditya Bhargava

Publisher Resources

ISBN: 9781789801217Supplemental Content