O'Reilly logo

Python Machine Learning By Example - Second Edition by Yuxi Liu

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required