Computing a Euclidean Distance Matrix Without Loops¶

IMPORTANT: Do not modify cells in this notebook unless instructed to do so.

About This Exercise¶

In the preceding activity, you derived a Euclidean distance matrix. Now that you have calculated the distance between points in terms of matrix operations, you are ready to write an efficient program that leverages NumPy's optimized functions. In this code exercise, rather than using loops, you will write a function to compute Euclidean distances between sets of vectors using NumPy functions.

Evaluation¶

This project must be successfully completed and submitted in order to receive credit for this course. Your score on this project will be included in your final grade calculation.

You are expected to write code where you see # YOUR CODE HERE within the cells of this notebook. Not all cells will be graded; code input cells followed by cells marked with # Auto-graded test cell will be graded. Upon submitting your work, the code you write at these designated positions will be assessed using an "auto-grader" that will run all test cells to assess your code. You will receive feedback from the auto-grader that will identify any errors in your code. Use this feedback to improve your code if you need to resubmit. Be sure not to change the names of any provided functions, classes, or variables within the existing code cells, as this will interfere with the auto-grader. Also, remember to execute all code cells sequentially, not just those you’ve edited, to ensure your code runs properly.

You can resubmit your work as many times as necessary before the submission deadline. If you experience difficulty or have questions about this exercise, use the Q&A discussion board to engage with your peers or seek assistance from the instructor.

Before starting your work, please review eCornell's policy regarding plagiarism (the presentation of someone else's work as your own without source credit).

Submit Code for Auto-Grader Feedback¶

Once you have completed your work on this notebook, you will submit your code for auto-grader review. Follow these steps:

  1. Save your notebook.

  2. Mark as Completed — In the blue menu bar along the top of this code exercise window, you’ll see a menu item called Education. In the Education menu, click Mark as Completed to submit your code for auto-grader/instructor review. This process will take a moment and a progress bar will show you the status of your submission.

  3. Review your results — Once your work is marked as complete, the results of the auto-grader will automatically be presented in a new tab within the code exercise window. You can click on the assessment name in this feedback window to see more details regarding specific feedback/errors in your code submission.

  4. Repeat, if necessary — The Jupyter Notebook will always remain accessible in the first tabbed window of the exercise. To reattempt the work, you will first need to click Mark as Uncompleted in the Education menu and then proceed to make edits to the notebook. Once you are ready to resubmit, follow steps one through three. You can repeat this procedure as many times as necessary.

You can also download a copy of this notebook in multiple formats using the Save and Export Notebook As option in the File menu above.

Import NumPy and Check Python Version¶

First, you must import NumPy, the Python package made for efficient matrix operations. Let's also check our version of Python. We've added the code for you for this first step.

In [1]:
import numpy as np
import time

import sys
sys.path.append("/home/codio/workspace/.modules")
from helper import *

print("Python version:", sys.version.split(" ")[0])
Python version: 3.12.5

Computing a Euclidean Distance Matrix the Slow Way¶

Many machine learning algorithms access their input data primarily through pairwise (Euclidean) distances, therefore it is important that we have a fast function that computes pairwise distances of input vectors.

Assume we have $n$ row data vectors $\mathbf{x}_1, \dotsc , \mathbf{x}_n \in \mathbb{R}^d$ and $m$ row vectors $\mathbf{z}_1, \dotsc , \mathbf{z}_m \in \mathbb{R}^d$. With these data vectors, let us define two matrices $\mathbf{X} = \left[ \mathbf{x}_1, \dotsc, \mathbf{x}_n \right]^\top \in \mathbb{R}^{n \times d}$, where the $i$-th row is vector $\mathbf{x}_i$, and $\mathbf{Z} = \left[ \mathbf{z}_1, \dotsc , \mathbf{z}_m \right]^\top \in \mathbb{R}^{m \times d}$. We want a distance function that takes as input these two matrices $\mathbf{X}$ and $\mathbf{Z}$ and outputs a matrix $\mathbf{D}\in \mathbb{R}^{n\times m}$, where the entries of $\mathbf{D}$ are given by

$$ \mathbf{D}_{ij} = \sqrt{ \smash[b]{ \left(\mathbf{x}_i - \mathbf{z}_j\right)^\top \left(\mathbf{x}_i - \mathbf{z}_j\right) } } $$

A naïve implementation to compute pairwise distances may look like the code below:

In [2]:
def L2distanceSlow(X, Z=None):
    """
    Computes the Euclidean distance (L2-distance) matrix very slowly
    using a naïve approach involving three nested for-loops.
    """
    if Z is None:
        Z = X

    n, d = X.shape        # Get shape of X
    m = Z.shape[0]        # Get number of rows in Z
    D = np.empty((n, m))  # Allocate memory for the output matrix
    
    # Use nested loops to compute the Euclidean distance matrix
    for i in range(n):          # Loop over vectors in X
        for j in range(m):      # Loop over vectors in Z
            for k in range(d):  # Loop over vector dimensions
                D[i, j] += (X[i, k] - Z[j, k]) ** 2
            
            # Compute Euclidean distance (L2-distance) between i-th and j-th vector    
            D[i, j] = np.sqrt(D[i, j])
    
    return D

Please read through the code above carefully and make sure you understand it. It is perfectly correct and will produce the correct result... eventually. To see what is wrong, try running the L2distanceSlow code below on an extremely small matrix X.

In [3]:
X = np.random.rand(700, 100)
print("Running the slow naïve version, please wait...")
%time Dslow = L2distanceSlow(X)
print("This is NOT an efficient way to compute the distance matrix!")
Running the slow naïve version, please wait...
CPU times: user 1min 39s, sys: 133 ms, total: 1min 39s
Wall time: 1min 39s
This is NOT an efficient way to compute the distance matrix!

This code defines some random data in $\mathbf{X}$ and computes the corresponding distance matrix $\mathbf{D}$. The %time statement determines how long this code takes to run. This implementation is much too slow for such a simple operation on a small amount of data, and writing code like this to deal with matrices in this course will result in code that takes days to run.

As a general rule, you should avoid tight loops at all cost. As you will see in the remainder of this exercise, you can do much better by performing bulk matrix operations using the NumPy package, which calls highly optimized compiled code behind the scenes.

Efficient Programming With NumPy¶

Although there is an execution overhead per line in Python, matrix operations are optimized and fast. In order to successfully program in this course, you need to free yourself from "for-loop thinking" and start thinking in terms of matrix operations. Python for scientific computing can be very fast if almost all the time is spent on a few heavy duty matrix operations. In this exercise, you will transform the function above into a few matrix operations without any loops at all.

The key to efficient programming in Python for machine learning, in general, is to think about it in terms of mathematics and not in terms of loops. In the following three exercises, you'll take the steps necessary to implement the euclidean distance function without loops.

Part One: Gram Matrix [Graded]¶

In [ ]:
 

Show that the Gram matrix (i.e., matrix of inner products) can be expressed in terms of pure matrix multiplication involving the matrices $\mathbf{X}$ and $\mathbf{Z}$.¶

Recall that the entries of the Gram matrix $\mathbf{G}$ are of the form:

$$ \mathbf{G}_{ij}=\mathbf{x}_i^\top\mathbf{z}_j $$

Once you are done with the derivation, implement the function gram_matrix below.

In [4]:
def gram_matrix(X, Z=None):
    """
    Computes the Gram matrix G; i.e., computes a matrix of consisting of
    inner products between the row vectors of two input matrices X and Z.
    
    Syntax: G = gram_matrix(X, Z); you can also call this function
            with only one input, i.e., gram_matrix(X) is equivalent
            to gram_matrix(X, X).
    
    Input:
        X: nxd data matrix with n vectors (rows) of dimensionality d
        Z: mxd data matrix with m vectors (rows) of dimensionality d

    Output:
        G: nxm matrix for which each entry G[i,j] is the inner-product
           between vectors X[i,:] and Z[j,:]
    """
    if Z is None:
        Z = X

    # YOUR CODE HERE
    G = X @ Z.T
    # END OF YOUR CODE

    return G

Run the next cell to check your implementation of gram_matrix.

In [5]:
def gram_matrix_test1():
    """
    Check output shape of your gram_matrix function using one input matrix
    """
    X = np.random.rand(700, 10)  # Random input matrix X with 700 samples
    return gram_matrix(X).shape == (700, 700)


def gram_matrix_test2():
    """
    Check output shape of your gram_matrix function using two input matrices
    """
    X = np.random.rand(700, 10)  # Random input matrix X with 700 samples
    Z = np.random.rand(200, 10)  # Random input matrix Z with 200 samples
    return gram_matrix(X, Z).shape == (700, 200)


def gram_matrix_test3():
    """
    Check output accuracy of your gram_matrix function using one input matrix
    """
    np.random.seed(1)               # Set random seed for consistency
    X = np.random.rand(700, 100)    # Random input matrix X with 700 samples
    G1 = gram_matrix(X)             # Compute the Gram matrix with your code
    G2 = gram_matrix_grader(X)      # Compute the Gram matrix with our code
    diff = np.linalg.norm(G1 - G2)  # Compute the difference (using norm)
    return diff < 1e-5              # Difference should be small


def gram_matrix_test4():
    """
    Check output accuracy of your gram_matrix function using two input matrices
    """
    np.random.seed(2)               # Set random seed for consistency
    X = np.random.rand(700, 100)    # Random input matrix X with 700 samples
    Z = np.random.rand(300, 100)    # Random input matrix Z with 300 samples
    G1 = gram_matrix(X, Z)          # Compute the Gram matrix with your code
    G2 = gram_matrix_grader(X, Z)   # Compute the Gram matrix with our code
    diff = np.linalg.norm(G1 - G2)  # Compute the difference (using norm)
    return diff < 1e-5              # Difference should be small


runtest(gram_matrix_test1, "gram_matrix_test1")
runtest(gram_matrix_test2, "gram_matrix_test2")
runtest(gram_matrix_test3, "gram_matrix_test3")
runtest(gram_matrix_test4, "gram_matrix_test4")
Running Test: gram_matrix_test1 ... ✔ Passed!
Running Test: gram_matrix_test2 ... ✔ Passed!
Running Test: gram_matrix_test3 ... ✔ Passed!
Running Test: gram_matrix_test4 ... ✔ Passed!

Skip over the auto-graded test cells below (see Evaluation for details).

In [6]:
# Auto-graded test cell worth one point (gram_matrix_test1)
In [7]:
# Auto-graded test cell worth one point (gram_matrix_test2)
In [8]:
# Auto-graded test cell worth one point (gram_matrix_test3)
In [9]:
# Auto-graded test cell worth one point (gram_matrix_test4)

Part Two: Implement calculate_S and calculate_R [Graded]¶

Recall that the element-wise squared Euclidean distance matrix $\mathbf{D}\odot\mathbf{D} \in \mathbb{R}^{n \times m}$ is defined by

$$ [\mathbf{D}\odot\mathbf{D}]_{ij} = \left(\mathbf{x}_i - \mathbf{z}_j\right)^\top \left(\mathbf{x}_i - \mathbf{z}_j\right) $$

Also, the matrices $\mathbf{S}, \mathbf{R} \in \mathbb{R}^{n \times m}$ are defined by

$$ \mathbf{S}_{ij} = \mathbf{x}_i^\top \mathbf{x}_i^ \quad \text{and} \quad \mathbf{R}_{ij} = \mathbf{z}_j^\top \mathbf{z}_j $$

In the previous activity, we showed that

$$ \mathbf{D}\odot\mathbf{D} = \mathbf{S} + \mathbf{R} - 2\mathbf{G} $$

Later in this exercise, you will implement L2distance to calculate $\mathbf{D}$. But you will need $\mathbf{S}$ and $\mathbf{R}$, which you will implement now in calculate_S and calculate_R, respectively. Ensure that your functions return $\mathbf{S}$ and $\mathbf{R}$ of size $n \times m$, as they will be added to $-2\mathbf{G}$ to get $\mathbf{D}\odot\mathbf{D}$.

Think about what the $\mathbf{S}$ and $\mathbf{R}$ matrices look like. You will find that the values in each row of $\mathbf{S}$ and the values in each column of $\mathbf{R}$ do not change! This is also apparent when considering that $\mathbf{S}_{ij} = \mathbf{x}_i^\top \mathbf{x}_i$ for all $j$; similar argument for $\mathbf{R}_{ij} = \mathbf{z}_j^\top \mathbf{z}_j$ for all $i$. That is,

$$ \mathbf{S} = \begin{bmatrix} \mathbf{x}_1^\top \mathbf{x}_1 & \mathbf{x}_1^\top \mathbf{x}_1 & \cdots & \mathbf{x}_1^\top \mathbf{x}_1 \\[5pt] \mathbf{x}_2^\top \mathbf{x}_2 & \mathbf{x}_2^\top \mathbf{x}_2 & \cdots & \mathbf{x}_2^\top \mathbf{x}_2 \\ \vdots & \vdots & \ddots & \vdots \\ \mathbf{x}_n^\top \mathbf{x}_n & \mathbf{x}_n^\top \mathbf{x}_n & \cdots & \mathbf{x}_n^\top \mathbf{x}_n \end{bmatrix} \quad \text{and} \quad \mathbf{R} = \begin{bmatrix} \mathbf{z}_1^\top \mathbf{z}_1 & \mathbf{z}_2^\top \mathbf{z}_2 & \cdots & \mathbf{z}_m^\top \mathbf{z}_m \\[5pt] \mathbf{z}_1^\top \mathbf{z}_1 & \mathbf{z}_2^\top \mathbf{z}_2 & \cdots & \mathbf{z}_m^\top \mathbf{z}_m \\ \vdots & \vdots & \ddots & \vdots \\ \mathbf{z}_1^\top \mathbf{z}_1 & \mathbf{z}_2^\top \mathbf{z}_2 & \cdots & \mathbf{z}_m^\top \mathbf{z}_m \end{bmatrix} $$

Now you just need to figure out how to calculate $\mathbf{x}_i^\top \mathbf{x}_i$ and $\mathbf{z}_j^\top \mathbf{z}_j$ without loops. You might find the fact $\mathbf{a}^\top \mathbf{a} = \sum_{k=1}^d a_k^2$ and repeat function np.repeat (and its axis parameter) useful.

In [35]:
def calculate_S(X, n, m):
    """
    function calculate_S(X)

    Computes the S matrix.
    Syntax:
    S=calculate_S(X)
    Input:
    X: nxd data matrix with n vectors (rows) of dimensionality d
    n: number of rows in X
    m: output number of columns in S

    Output:
    Matrix S of size nxm
    S[i,j] is the inner-product between vectors X[i,:] and X[i,:]
    """
    assert n == X.shape[0]

    # YOUR CODE HERE
    # stretch sideways
    S = np.repeat(
            np.sum(X**2, axis=1).reshape(-1,1),
            m,
            axis=1)
    # END OF YOUR CODE

    return S
In [36]:
def calculate_R(Z, n, m):
    """
    function calculate_R(Z)

    Computes the R matrix.
    Syntax:
    R=calculate_R(Z)
    Input:
    Z: mxd data matrix with m vectors (rows) of dimensionality d
    n: output number of rows in Z
    m: number of rows in Z

    Output:
    Matrix R of size nxm
    R[i,j] is the inner-product between vectors Z[j,:] and Z[j,:]
    """
    assert m == Z.shape[0]

    # YOUR CODE HERE
    R = np.repeat(
        np.sum(Z**2, axis=1).reshape(1,-1),
        n,
        axis=0
    )
    # END OF YOUR CODE

    return R

Run the next cell to check your implementation of calculate_S and calculate_R.

In [37]:
def calculate_S_test1():
    """
    Check that the output of your calculate_S function has the correct shape
    """
    X = np.random.rand(700, 100)  # Random input matrix X
    Z = np.random.rand(800, 100)  # Random input matrix Z
    n, _ = X.shape                # Get number of rows in X
    m, _ = Z.shape                # Get number of rows in Z
    S = calculate_S(X, n, m)      # Compute your matrix S
    return S.shape == (n, m)      # Shape should be (n, m)


def calculate_S_test2():
    """
    Check that the output of your calculate_S function has the correct value
    """
    np.random.seed(1)                 # Set random seed for consistency
    X = np.random.rand(700, 100)      # Random input matrix X
    Z = np.random.rand(800, 100)      # Random input matrix Z
    n, _ = X.shape                    # Get number of rows in X
    m, _ = Z.shape                    # Get number of rows in Z
    S1 = calculate_S(X, n, m)         # Compute your matrix S
    S2 = calculate_S_grader(X, n, m)  # Compute our matrix S
    diff = np.linalg.norm(S1 - S2)    # Compute the difference
    return diff < 1e-5                # Difference should be small


def calculate_R_test1():
    """
    Check that the output of your calculate_R function has the correct shape
    """
    X = np.random.rand(700, 100)  # Random input matrix X
    Z = np.random.rand(800, 100)  # Random input matrix Z
    n, _ = X.shape                # Get number of rows in X
    m, _ = Z.shape                # Get number of rows in Z
    R = calculate_R(Z, n, m)      # Compute your matrix R
    return R.shape == (n, m)      # Shape should be (n, m) 


def calculate_R_test2():
    """
    Check that the output of your calculate_R function has the correct value
    """
    np.random.seed(2)                 # Set random seed for consistency
    X = np.random.rand(700, 100)      # Random input matrix X
    Z = np.random.rand(800, 100)      # Random input matrix Z
    n, _ = X.shape                    # Get number of rows in X
    m, _ = Z.shape                    # Get number of rows in Z
    R1 = calculate_R(Z, n, m)         # Compute your matrix R
    R2 = calculate_R_grader(Z, n, m)  # Compute our matrix R
    diff = np.linalg.norm(R1 - R2)    # Compute the difference
    return diff < 1e-5                # Difference should be small


runtest(calculate_S_test1, "calculate_S_test1")
runtest(calculate_S_test2, "calculate_S_test2")
runtest(calculate_R_test1, "calculate_R_test1")
runtest(calculate_R_test2, "calculate_R_test2")
Running Test: calculate_S_test1 ... ✔ Passed!
Running Test: calculate_S_test2 ... ✔ Passed!
Running Test: calculate_R_test1 ... ✔ Passed!
Running Test: calculate_R_test2 ... ✔ Passed!

Skip over the auto-graded test cells below (see Evaluation for details).

In [38]:
# Auto-graded test cell worth one point (calculate_S_test1)
In [39]:
# Auto-graded test cell worth one point (calculate_S_test2)
In [40]:
# Auto-graded test cell worth one point (calculate_R_test1)
In [41]:
# Auto-graded test cell worth one point (calculate_R_test2)

Part Three: Implement L2distance [Graded]¶

In this exercise, you will use the above formula to implement the function L2distance, which computes the Euclidean distance matrix $\mathbf{D}$ without a single loop.

Recall that the element-wise square of $\mathbf{D}$ is of the form

$$ \mathbf{D}\odot\mathbf{D} = \mathbf{S} + \mathbf{R} - 2\mathbf{G} $$

and the entries of $\mathbf{D}$ are

$$ \mathbf{D}_{ij} = \sqrt{ \smash[b]{[\mathbf{D}\odot\mathbf{D}]_{ij}} } $$

Hint: Make sure that when you take the square root of the squared distance matrix, ensure that all entries are non-negative. Sometimes very small positive numbers can become negative due to numerical imprecision. Knowing that all distances must always be non-negative, you can simply overwrite all negative values with 0.0 to avoid unintended consequences.

In [46]:
def L2distance(X, Z=None):
    """
    Efficiently computes the Euclidean distance (L2-distance) matrix.
    
    Syntax: D = L2distance(X, Z); or you can call L2distance with only one
            input because D = L2distance(X) is equivalent to D = L2distance(X, X)
    
    Input:
        X: nxd data matrix with n vectors (rows) of dimensionality d
        Z: mxd data matrix with m vectors (rows) of dimensionality d

    Output:
        D: nxm matrix such that each entry D[i, j] is the Euclidean distance
           (L2-distance) between the two row vectors X[i, :] and Z[j, :]
    """
    if Z is None:
        Z = X

    n, d1 = X.shape
    m, d2 = Z.shape
    assert d1 == d2, "Dimensions of input vectors must match!"
    
    # YOUR CODE HERE
    S = calculate_S(X, n, m)
    R = calculate_R(Z, n, m)
    G = gram_matrix(X,Z)
    D2 = (S + R - 2*G)
    D = np.sqrt(np.maximum(D2, 0))
    # END OF YOUR CODE

    return D

Run the next cell to check your implementation of L2distance.

In [47]:
def L2distance_test1():
    """
    Check that your distance matrix has the correct shape
    """
    X = np.random.rand(700, 100)  # Random input matrix X
    Z = np.random.rand(800, 100)  # Random input matrix Z
    n, _ = X.shape                # Get number of rows in X
    m, _ = Z.shape                # Get number of rows in Z
    D = L2distance(X, Z)          # Compute your distance matrix
    return D.shape == (n, m)

def L2distance_test2():
    """
    Check your distance matrix against our distance matrix
    """
    np.random.seed(1)               # Set random seed for consistency
    X = np.random.rand(700, 100)    # Random input matrix X
    D1 = L2distance(X)              # Compute your distance matrix
    D2 = L2distance_grader(X)       # Compute our distance matrix
    diff = np.linalg.norm(D1 - D2)  # Compute the difference (using norm)
    return diff < 1e-5              # Difference should be small


def L2distance_test3():
    """
    Another check of your distance matrix against our distance matrix
    """
    np.random.seed(2)                 # Set random seed for consistency
    X = np.random.rand(700, 100)      # Random input matrix X
    D1 = L2distance(X)                # Compute your distance matrix
    D2sq = L2distance_grader(X) ** 2  # Compute our squared distance matrix
    diff = np.linalg.norm(D1 - D2sq)  # Compute the difference (using norm)
    return diff > 100                 # Difference should be big


def L2distance_test4():
    """
    Another check of your distance matrix against our distance matrix
    """
    np.random.seed(3)               # Set random seed for consistency
    X = np.random.rand(700, 100)    # Random input matrix X
    Z = np.random.rand(300, 100)    # Random input matrix Z
    D1 = L2distance(X, Z)           # Compute your distance matrix
    D2 = L2distance_grader(X, Z)    # Compute our distance matrix
    diff = np.linalg.norm(D1 - D2)  # Compute the difference (using norm)
    return diff < 1e-5              # Difference should be small


runtest(L2distance_test1, "L2distance_test1")
runtest(L2distance_test2, "L2distance_test2")
runtest(L2distance_test3, "L2distance_test3")
runtest(L2distance_test4, "L2distance_test4")
Running Test: L2distance_test1 ... ✔ Passed!
Running Test: L2distance_test2 ... ✔ Passed!
Running Test: L2distance_test3 ... ✔ Passed!
Running Test: L2distance_test4 ... ✔ Passed!

Skip over the auto-graded test cells below (see Evaluation for details).

In [48]:
# Auto-graded test cell worth one point (L2distance_test1)
In [49]:
# Auto-graded test cell worth one point (L2distance_test2)
In [50]:
# Auto-graded test cell worth one point (L2distance_test3)
In [51]:
# Auto-graded test cell worth one point (L2distance_test4)

Let's now compare the speed of your L2distance function against the previous naïve implementation:

In [52]:
current_time = lambda: int(round(time.time() * 1000))

X = np.random.rand(700, 100)
Z = np.random.rand(300, 100)

print("Running the slow naïve version...")
before = current_time()
Dslow = L2distanceSlow(X)
after = current_time()
t_slow = after - before
print(f"{t_slow:.2f} ms\n")

print("Running the vectorized version...")
before = current_time()
Dfast = L2distance(X)
after = current_time()
t_fast = after - before
print(f"{t_fast:.2f} ms\n")

diff = np.linalg.norm(Dfast - Dslow)
speedup = t_slow / t_fast
print(f"The difference between the result of these two methods should be very small: {diff:.8f}")
print(f"However, your NumPy code was {speedup:.2f} times faster!")
Running the slow naïve version...
104394.00 ms

Running the vectorized version...
24.00 ms

The difference between the result of these two methods should be very small: 0.00000215
However, your NumPy code was 4349.75 times faster!

How much faster is your code now? With this implementation, you should easily be able to compute the distances between many more vectors. It should be clear now, even for small datasets, that the for-loop based implementation could take several days or even weeks to perform basic operations that take seconds or minutes with well-written NumPy code.