|
| 1 | +# This code is supporting material for the book |
| 2 | +# Building Machine Learning Systems with Python |
| 3 | +# by Willi Richert and Luis Pedro Coelho |
| 4 | +# published by PACKT Publishing |
| 5 | +# |
| 6 | +# It is made available under the MIT License |
| 7 | + |
| 8 | +COLOUR_FIGURE = False |
| 9 | + |
| 10 | +from matplotlib import pyplot as plt |
| 11 | +from matplotlib.colors import ListedColormap |
| 12 | +from load import load_dataset |
| 13 | +import numpy as np |
| 14 | +from sklearn.neighbors import KNeighborsClassifier |
| 15 | +from knn import fit_model, predict |
| 16 | + |
| 17 | +feature_names = [ |
| 18 | + 'area', |
| 19 | + 'perimeter', |
| 20 | + 'compactness', |
| 21 | + 'length of kernel', |
| 22 | + 'width of kernel', |
| 23 | + 'asymmetry coefficien', |
| 24 | + 'length of kernel groove', |
| 25 | +] |
| 26 | + |
| 27 | + |
| 28 | +def plot_decision(features, labels): |
| 29 | + '''Plots decision boundary for KNN |
| 30 | +
|
| 31 | + Parameters |
| 32 | + ---------- |
| 33 | + features : ndarray |
| 34 | + labels : sequence |
| 35 | +
|
| 36 | + Returns |
| 37 | + ------- |
| 38 | + fig : Matplotlib Figure |
| 39 | + ax : Matplotlib Axes |
| 40 | + ''' |
| 41 | + y0, y1 = features[:, 2].min() * .9, features[:, 2].max() * 1.1 |
| 42 | + x0, x1 = features[:, 0].min() * .9, features[:, 0].max() * 1.1 |
| 43 | + X = np.linspace(x0, x1, 100) |
| 44 | + Y = np.linspace(y0, y1, 100) |
| 45 | + X, Y = np.meshgrid(X, Y) |
| 46 | + |
| 47 | + model = KNeighborsClassifier(1) |
| 48 | + model.fit(features[:, (0,2)], labels) |
| 49 | + C = model.predict(np.vstack([X.ravel(), Y.ravel()]).T).reshape(X.shape) |
| 50 | + if COLOUR_FIGURE: |
| 51 | + cmap = ListedColormap([(1., .6, .6), (.6, 1., .6), (.6, .6, 1.)]) |
| 52 | + else: |
| 53 | + cmap = ListedColormap([(1., 1., 1.), (.2, .2, .2), (.6, .6, .6)]) |
| 54 | + fig,ax = plt.subplots() |
| 55 | + ax.set_xlim(x0, x1) |
| 56 | + ax.set_ylim(y0, y1) |
| 57 | + ax.set_xlabel(feature_names[0]) |
| 58 | + ax.set_ylabel(feature_names[2]) |
| 59 | + ax.pcolormesh(X, Y, C, cmap=cmap) |
| 60 | + if COLOUR_FIGURE: |
| 61 | + cmap = ListedColormap([(1., .0, .0), (.0, 1., .0), (.0, .0, 1.)]) |
| 62 | + ax.scatter(features[:, 0], features[:, 2], c=labels, cmap=cmap) |
| 63 | + else: |
| 64 | + for lab, ma in zip(range(3), "Do^"): |
| 65 | + ax.plot(features[labels == lab, 0], features[ |
| 66 | + labels == lab, 2], ma, c=(1., 1., 1.)) |
| 67 | + return fig,ax |
| 68 | + |
| 69 | + |
| 70 | +features, labels = load_dataset('seeds') |
| 71 | +names = sorted(set(labels)) |
| 72 | +labels = np.array([names.index(ell) for ell in labels]) |
| 73 | + |
| 74 | +fig,ax = plot_decision(features, labels) |
| 75 | +fig.savefig('figure4sklearn.png') |
| 76 | + |
| 77 | +features -= features.mean(0) |
| 78 | +features /= features.std(0) |
| 79 | +fig,ax = plot_decision(features, labels) |
| 80 | +fig.savefig('figure5sklearn.png') |
0 commit comments