Write two functions; One should return the distance measures using Euclidean distance and another one should use mahalanobis distance measure.

# How to write functions for calculating Euclidean distance and mahalanobis distance?

**pjoshi15**#2

Hi @wehired you can use scipy’s functions scipy.spatial.distance.euclidean( ) andscipy.spatial.distance.mahalanobis( ) to calculate Euclidean and Mahalanobis distance, respectively.

**PulkitS**#3

Hi @wehired,

Do you want to write the code from scratch?

You can use the predefined functions as well to calculate these distances.

**Euclidean Distance**

```
from scipy.spatial import distance
dst = distance.euclidean(a, b) # where a and b are two arrays
```

**mahalanobis distance**

```
from scipy.spatial import distance
dst = distance.mahalanobis(a,b,VI) # here a and b are arrays and VI is the inverse of covariance matrix
```

Refer here for more details.

**wehired**#4

Thank you very much to give euclidean and Mahalanobis functions but as a beginner am still finding it hard to apply it below; please let some one show me how.

Formulate a real world classification task/problem- whose dataset can be applied on a KNN algorithm to design a machine learning model that can be used to solve the task/problem in future. This part includes various activities such as:

- Generating the task be a binary label
- Generating the dataset (a minimum of 50 records), this can be a binary labelled data set or multi-class dataset.
- Separate the features from the labels using the slice method of lists, split the dataset into two: train and test using the train-test split on a ratio of 0.2
- Using the sklearn documentation on KNN, train the algorithm on the KNN classifier and the train dataset.
- Run a predict function on the test set.

Warm regards,

Lamech