Docsity

K Nearest Neighbour Machine Learning algorithms, Assignments of Computer science

Toggle sidebar
bg1
Load Dataset into a Pandas DataFrame
In [54]:
In [55]:
Get Features into a NumPy Array
In [57]:
In [58]:
Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species
01 5.1 3.5 1.4 0.2 Iris-setosa
12 4.9 3.0 1.4 0.2 Iris-setosa
23 4.7 3.2 1.3 0.2 Iris-setosa
34 4.6 3.1 1.5 0.2 Iris-setosa
45 5.0 3.6 1.4 0.2 Iris-setosa
... ... ... ... ... ... ...
145 146 6.7 3.0 5.2 2.3 Iris-virginica
146 147 6.3 2.5 5.0 1.9 Iris-virginica
147 148 6.5 3.0 5.2 2.0 Iris-virginica
148 149 6.2 3.4 5.4 2.3 Iris-virginica
149 150 5.9 3.0 5.1 1.8 Iris-virginica
150 6 l
(150, 2)
Out[58]:
array([[1.4, 0.2],
[1.4, 0.2],
[1.3, 0.2],
[1.5, 0.2],
[1.4, 0.2]])
# k-Nearest Neighbor Model
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df_iris=pd.read_csv('C:/Users/kriti/Downloads/Iris.csv')
df_iris
X = df_iris[['PetalLengthCm', 'PetalWidthCm']].values
print(X.shape)
X[:5, :]
1
1
2
3
1
2
1
2
1
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download K Nearest Neighbour Machine Learning algorithms and more Assignments Computer science in PDF only on Docsity!

Load Dataset into a Pandas DataFrame In [54]: In [55]: Get Features into a NumPy Array In [57]: In [58]: Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species 0 1 5.1 3.5 1.4 0.2 Iris-setosa 1 2 4.9 3.0 1.4 0.2 Iris-setosa 2 3 4.7 3.2 1.3 0.2 Iris-setosa 3 4 4.6 3.1 1.5 0.2 Iris-setosa 4 5 5.0 3.6 1.4 0.2 Iris-setosa ... ... ... ... ... ... ... 145 146 6.7 3.0 5.2 2.3 Iris-virginica 146 147 6.3 2.5 5.0 1.9 Iris-virginica 147 148 6.5 3.0 5.2 2.0 Iris-virginica 148 149 6.2 3.4 5.4 2.3 Iris-virginica 149 150 5.9 3.0 5.1 1.8 Iris-virginica 150 6 l (150, 2) Out[58]: array([[1.4, 0.2], [1.4, 0.2], [1.3, 0.2], [1.5, 0.2], [1.4, 0.2]])

# k-Nearest Neighbor Model

import pandas as pd import numpy as np import matplotlib.pyplot as plt df_iris = pd.read_csv('C:/Users/kriti/Downloads/Iris.csv') df_iris X = df_iris[['PetalLengthCm', 'PetalWidthCm']].values print(X.shape) X[: 5 , :]

Get Class Labels into a NumPy Array Similary to assigning the features to a new variable X, we are now assigning the class lables to a new variable, which we will call y. However, before we do that, let us map the class labels from a string representation into an int (integer) format. For this, we add a new column ClassLabel to the data frame: In [60]: In [61]: In [62]: Out[60]: Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species ClassLabel 145 146 6.7 3.0 5.2 2.3 (^) virginicaIris- 2 146 147 6.3 2.5 5.0 1.9 (^) virginicaIris- 2 147 148 6.5 3.0 5.2 2.0 (^) virginicaIris- 2 148 149 6.2 3.4 5.4 2.3 (^) virginicaIris- 2 149 150 5.9 3.0 5.1 1.8 Iris- virginica 2 Out[61]: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int64) Out[62]: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int64) label_dict = {'Iris-setosa': 0 , 'Iris-versicolor': 1 , 'Iris-virginica': 2 } df_iris['ClassLabel'] = df_iris['Species'].map(label_dict) df_iris.tail() y = df_iris['ClassLabel'].values y y[: 10 ]

Out[52]: array([[5.1, 3.5, 1.4, 0.2], [4.9, 3. , 1.4, 0.2], [4.7, 3.2, 1.3, 0.2], [4.6, 3.1, 1.5, 0.2], [5. , 3.6, 1.4, 0.2], [5.4, 3.9, 1.7, 0.4], [4.6, 3.4, 1.4, 0.3], [5. , 3.4, 1.5, 0.2], [4.4, 2.9, 1.4, 0.2], [4.9, 3.1, 1.5, 0.1], [5.4, 3.7, 1.5, 0.2], [4.8, 3.4, 1.6, 0.2], [4.8, 3. , 1.4, 0.1], [4.3, 3. , 1.1, 0.1], [5.8, 4. , 1.2, 0.2], [5.7, 4.4, 1.5, 0.4], [5.4, 3.9, 1.3, 0.4], [5.1, 3.5, 1.4, 0.3], # gives the values of input features iris.data

.. _iris_dataset: Iris plants dataset


Data Set Characteristics: :Number of Instances: 150 (50 in each of three classes) :Number of Attributes: 4 numeric, predictive attributes and the class :Attribute Information:

  • sepal length in cm
  • sepal width in cm
  • petal length in cm
  • petal width in cm
  • class:
    • Iris-Setosa
    • Iris-Versicolour
    • Iris-Virginica :Summary Statistics: ============== ==== ==== ======= ===== ==================== Min Max Mean SD Class Correlation ============== ==== ==== ======= ===== ==================== sepal length: 4.3 7.9 5.84 0.83 0. sepal width: 2.0 4.4 3.05 0.43 -0. petal length: 1.0 6.9 3.76 1.76 0.9490 (high!) petal width: 0.1 2.5 1.20 0.76 0.9565 (high!) ============== ==== ==== ======= ===== ==================== :Missing Attribute Values: None :Class Distribution: 33.3% for each of 3 classes. :Creator: R.A. Fisher :Donor: Michael Marshall (MARSHALL%[email protected]) :Date: July, 1988 The famous Iris database, first used by Sir R.A. Fisher. The dataset is ta ken from Fisher's paper. Note that it's the same as in R, but not as in the UC I Machine Learning Repository, which has two wrong data points. This is perhaps the best known database to be found in the pattern recognition literature. Fisher's paper is a classic in the field and is referenced frequently to this day. (See Duda & Hart, for example.) Th e data set contains 3 classes of 50 instances each, where each class refers to a type of iris plant. One class is linearly separable from the other 2; the latter are NOT linearly separable from each other. .. topic:: References
  • Fisher, R.A. "The use of multiple measurements in taxonomic problems" # print description of the iris dataset print(iris.DESCR)

from mlxtend.plotting import scatterplotmatrix import matplotlib.pyplot as plt names = ['sepal length [cm]', 'sepal width [cm]', 'petal length [cm]', 'petal width [cm]'] fig, axes = scatterplotmatrix(iris.data[y == 0 ], figsize = ( 10 , 8 ), alpha = 0.5) fig, axes = scatterplotmatrix(iris.data[y == 1 ], fig_axes = (fig, axes), alpha = 0.5) fig, axes = scatterplotmatrix(iris.data[y == 2 ], fig_axes = (fig, axes), alpha = 0.5, names = n plt.legend(names) plt.tight_layout() plt.show()

There is a convenient functions in scikit-learn that allow us to do the exact same things in much fewer lines of code. I.e., the following code will load the iris dataset and split it into 30% test data and 70% training data: Out[17]: array([[5.1, 3.5, 1.4, 0.2], [4.9, 3. , 1.4, 0.2], [4.7, 3.2, 1.3, 0.2], [4.6, 3.1, 1.5, 0.2], [5. , 3.6, 1.4, 0.2], [5.4, 3.9, 1.7, 0.4], [4.6, 3.4, 1.4, 0.3], [5. , 3.4, 1.5, 0.2], [4.4, 2.9, 1.4, 0.2], [4.9, 3.1, 1.5, 0.1], [5.4, 3.7, 1.5, 0.2], [4.8, 3.4, 1.6, 0.2], [4.8, 3. , 1.4, 0.1], [4.3, 3. , 1.1, 0.1], [5.8, 4. , 1.2, 0.2], [5.7, 4.4, 1.5, 0.4], [5.4, 3.9, 1.3, 0.4], [5.1, 3.5, 1.4, 0.3], [5.7, 3.8, 1.7, 0.3], [5.1, 3.8, 1.5, 0.3], [5.4, 3.4, 1.7, 0.2], [5.1, 3.7, 1.5, 0.4], [4.6, 3.6, 1. , 0.2], [5.1, 3.3, 1.7, 0.5], [4.8, 3.4, 1.9, 0.2], [5. , 3. , 1.6, 0.2], [5. , 3.4, 1.6, 0.4], [5.2, 3.5, 1.5, 0.2], [5.2, 3.4, 1.4, 0.2], [4.7, 3.2, 1.6, 0.2], [4.8, 3.1, 1.6, 0.2], [5.4, 3.4, 1.5, 0.4], [5.2, 4.1, 1.5, 0.1], [5.5, 4.2, 1.4, 0.2], [4.9, 3.1, 1.5, 0.2], [5. , 3.2, 1.2, 0.2], [5.5, 3.5, 1.3, 0.2], [4.9, 3.6, 1.4, 0.1], [4.4, 3. , 1.3, 0.2], [5.1, 3.4, 1.5, 0.2], [5. , 3.5, 1.3, 0.3], [4.5, 2.3, 1.3, 0.3], [4.4, 3.2, 1.3, 0.2], [5. , 3.5, 1.6, 0.6], [5.1, 3.8, 1.9, 0.4], [4.8, 3. , 1.4, 0.3], [5.1, 3.8, 1.6, 0.2], [4.6, 3.2, 1.4, 0.2], [5.3, 3.7, 1.5, 0.2], [5. , 3.3, 1.4, 0.2]]) 1 iris.data[y == 0 ]

In [79]: In [80]: Visualize Decision Boundary Usually, in machine learning, we work with datasets that have more then 2 feature variables. For educational purposes, however, we chose a very simple dataset consisting of only two features here (the petal length and the petal width of Iris flowers). If we have only two features, we can easily visualize the decision boundary of the model -- here, we will be using a convenience function I implemented in the MLxtend library: Out[79]: array([1, 2, 2, 1, 0, 2, 1, 0, 0, 1, 2, 0, 1, 2, 2, 2, 0, 0, 1, 0, 0, 1, 0, 2, 0, 0, 0, 2, 2, 0, 2, 1, 0, 0, 1, 1, 2, 0, 0, 1, 1, 0, 2, 2, 2]) Test set accuracy: 95.56% y_pred = knn_model.predict(X_test) y_pred num_correct_predictions = (y_pred == y_test).sum() accuracy = (num_correct_predictions / y_test.shape[ 0 ]) ***** 100 # print('Test set accuracy: %.2f%%' % accuracy) print(f'Test set accuracy: {accuracy:.2f}%')

In [72]: In [ ]: from mlxtend.plotting import plot_decision_regions plot_decision_regions(X_train, y_train, knn_model) plt.xlabel('petal length [cm]') plt.ylabel('petal width [cm]') plt.legend(loc = 'upper left') plt.show() plot_decision_regions(X_test, y_test, knn_model) plt.xlabel('petal length [cm]') plt.ylabel('petal width [cm]') plt.legend(loc = 'upper left') plt.show()