Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
50 Algorithms Every Programmer Should Know - Second Edition

You're reading from  50 Algorithms Every Programmer Should Know - Second Edition

Product type Book
Published in Sep 2023
Publisher Packt
ISBN-13 9781803247762
Pages 538 pages
Edition 2nd Edition
Languages
Author (1):
Imran Ahmad Imran Ahmad
Profile icon Imran Ahmad

Table of Contents (22) Chapters

Preface 1. Section 1: Fundamentals and Core Algorithms
2. Overview of Algorithms 3. Data Structures Used in Algorithms 4. Sorting and Searching Algorithms 5. Designing Algorithms 6. Graph Algorithms 7. Section 2: Machine Learning Algorithms
8. Unsupervised Machine Learning Algorithms 9. Traditional Supervised Learning Algorithms 10. Neural Network Algorithms 11. Algorithms for Natural Language Processing 12. Understanding Sequential Models 13. Advanced Sequential Modeling Algorithms 14. Section 3: Advanced Topics
15. Recommendation Engines 16. Algorithmic Strategies for Data Handling 17. Cryptography 18. Large-Scale Algorithms 19. Practical Considerations 20. Other Books You May Enjoy
21. Index

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 cluster
import pandas as pd
import 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 = cluster.KMeans(n_clusters=2)
myKmeans.fit(dataset)
  1. Let's create a variable named centroid that is an array that holds the location of the center...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}