Learn
Distance Formula
SciPy Distances

Now that you’ve written these three distance formulas yourself, let’s look at how to use them using Python’s SciPy library:

  • Euclidean Distance .euclidean()
  • Manhattan Distance .cityblock()
  • Hamming Distance .hamming()

There are a few noteworthy details to talk about:

First, the scipy implementation of Manhattan distance is called cityblock(). Remember, computing Manhattan distance is like asking how many blocks away you are from a point.

Second, the scipy implementation of Hamming distance will always return a number between 0 an 1. Rather than summing the number of differences in dimensions, this implementation sums those differences and then divides by the total number of dimensions. For example, in your implementation, the Hamming distance between [1, 2, 3] and [7, 2, -10] would be 2. In scipy‘s version, it would be 2/3.

Instructions

1.

Call distance.euclidean() using the points [1, 2] and [4, 0] as parameters.

Print the result.

2.

Call distance.cityblock() using the points [1, 2] and [4, 0] as parameters.

Print the result.

3.

Call distance.hamming() using [5, 4, 9] and [1, 7, 9] as parameters and print the results.

Your answer shouldn’t match your function’s results. Remember, scipy divides by the number of dimensions.

Folder Icon

Sign up to start coding

Already have an account?