2.1. Exercises

Calculating Distances

u = np.array([5, 0, 22, -11])
v = np.array([-1, 0, 19, -9])

We have collected a third vector w.

u = np.array([5, 0, 22, -11])
v = np.array([-1, 0, 19, -9])
w = np.array([0, 1, 17, -4])

Distance True or False


Instructions:
Running a coding exercise for the first time could take a bit of time for everything to load. Be patient, it could take a few minutes.

When you see ____ in a coding exercise, replace it with what you assume to be the correct code. Run it and see if you obtain the desired output. Submit your code to validate if you were correct.

Make sure you remove the hash (#) symbol in the coding portions of this question. We have commented them so that the line won’t execute and you can test your code after each step.

Calculating Euclidean Distance Step by Step

Let’s calculate the Euclidean distance between 2 examples in the Pokémon dataset without using Scikit-learn.

Tasks:

  • Subtract the first two pokemon feature vectors and save the result in an object named sub_pk.
  • Square the difference and save it in an object named sq_sub_pk.
  • Sum the squared difference from each dimension and save the result in an object named sss_pk.
  • Finally, take the square root of the entire calculation and save it in an object named pk_distance.
Hint 1
  • Are you using X.iloc[1] - X.iloc[0] to subtract the first 2 Pokémon feature vectors?
  • Are you using **2 to square the difference??
  • Are you using .sum() to sum the differences?
  • Are you using sqrt() to square root the sum of squared differences?
Fully worked solution:


Calculating Euclidean Distance with Scikit-learn

This time, let’s calculate the Euclidean distance between 2 examples in the Pokémon dataset using Scikit-learn.

Task:

  • Calculate the Euclidean distance of the first 2 Pokémon and save it in an object named pk_distance.
Hint 1
  • Are you making sure to use euclidean_distances(X.iloc[:2])
  • Are you selecting the right value from the array using [0,1]
Fully worked solution: