Skip to Content
Python Machine Learning By Example - Second Edition
book

Python Machine Learning By Example - Second Edition

by Yuxi (Hayden) Liu
February 2019
Beginner to intermediate
382 pages
10h 1m
English
Packt Publishing
Content preview from Python Machine Learning By Example - Second Edition

Implementing k-means from scratch

We use the iris dataset from scikit-learn as an example. Let's first load the data and visualize it. We herein only use two features out of the original four for simplicity:

>>> from sklearn import datasets>>> iris = datasets.load_iris()>>> X = iris.data[:, 2:4]>>> y = iris.target

Since the dataset contains three iris classes, we plot it in three different colors, as follows:

>>> import numpy as np>>> from matplotlib import pyplot as plt>>> y_0 = np.where(y==0)>>> plt.scatter(X[y_0, 0], X[y_0, 1])>>> y_1 = np.where(y==1)>>> plt.scatter(X[y_1, 0], X[y_1, 1])>>> y_2 = np.where(y==2)>>> plt.scatter(X[y_2, 0], X[y_2, 1])>>> plt.show()

This will give you the following output for the origin data plot:

Assuming ...

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

Python Machine Learning by Example - Third Edition

Python Machine Learning by Example - Third Edition

Yuxi (Hayden) Liu
Python Machine Learning, Second Edition - Second Edition

Python Machine Learning, Second Edition - Second Edition

Sebastian Raschka, Jared Huffman, Vahid Mirjalili, Ryan Sun

Publisher Resources

ISBN: 9781789616729Supplemental Content