Implementing Minkowski Distance Metric

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to implement the Minkowski distance function, a generalized distance metric that includes commonly used distance measures like Euclidean and Manhattan distances. You will also learn how to test and refine the function, as well as how to integrate it into a larger project.

🎯 Tasks

In this project, you will learn:

  • How to implement the Minkowski distance function in Python
  • How to test the Minkowski distance function with different input parameters
  • How to refine the Minkowski distance function to handle edge cases
  • How to integrate the Minkowski distance function into a larger project

🏆 Achievements

After completing this project, you will be able to:

  • Calculate Minkowski distances between two points
  • Handle different types of input parameters for the Minkowski distance function
  • Test and refine a function to improve its robustness
  • Integrate a custom function into a larger project

Implement the Minkowski Distance Function

In this step, you will learn how to implement the Minkowski distance function in Python. Follow the steps below to complete this step:

Open the minkowski_distance.py file in your code editor.

Implement the minkowski_distance function with the following logic:

from typing import List, Union
import numpy as np

def minkowski_distance(
    point_a: List[float], point_b: List[float], p: Union[int, str]
) -> float:
    """
    Calculate the Minkowski distance between two points.

    This function computes the Minkowski distance between two points represented as lists
    of numerical values. The Minkowski distance is a generalization of other distance
    metrics like Euclidean and Manhattan distances.

    Parameters:
    - point_a (List[float]): The coordinates of the first point.
    - point_b (List[float]): The coordinates of the second point.
    - p (Union[int, str]): The exponent parameter for the Minkowski distance calculation.
      - If p is an integer greater than or equal to 1, the p-norm distance is calculated.
      - If p is 'INF', the infinity-norm (Chebyshev) distance is calculated.

    Returns:
    - float: The Minkowski distance between the two points. If an invalid value of p is
      provided, it returns -1.
    """

    if isinstance(p, int) and p >= 1:
        distance = np.power(
            np.sum(np.abs(np.array(point_a) - np.array(point_b)) ** p), 1 / p
        )
    elif p == "INF":
        distance = np.max(np.abs(np.array(point_a) - np.array(point_b)))
    else:
        distance = -1
    return float(distance)

Explanation

First, we import the necessary modules.

Then, define the minkowski_distance function that takes three parameters: point_a, point_b, and p.

The function calculates the Minkowski distance:

  • If p is an integer greater than or equal to 1, it calculates the p-norm distance using the formula:
    [
    \text{distance} = \left( \sum \left| \text{point_a} - \text{point_b} \right|^p \right)^{1/p}
    ]
  • If p is "INF", it calculates the infinity-norm (Chebyshev) distance using the formula:
    [
    \text{distance} = \max \left| \text{point_a} - \text{point_b} \right|
    ]
  • If p is not valid, it returns -1.0.
✨ Check Solution and Practice

Test the Minkowski Distance Function

In this step, you will test the minkowski_distance function with different input parameters. Follow the steps below to complete this step:

Open the minkowski_distance.py file in your code editor.

Add the following test cases at the bottom of the file:

if __name__ == "__main__":
    a = [1, 0]
    b = [2, 0]
    p = 2
    distance = minkowski_distance(a, b, p)
    print(f"{a=}, {b=}, {p=}, {distance=}")  ## Expected output: a=[1, 0], b=[2, 0], p=2, distance=1.0

    a = [4, 9, 10]
    b = [2, 0, -3]
    p = "INF"
    distance = minkowski_distance(a, b, p)
    print(f"{a=}, {b=}, {p=}, {distance=}")  ## Expected output: a=[4, 9, 10], b=[2, 0, -3], p=INF, distance=13.0

    a = [1, 4, 10, 0]
    b = [20, -3, -5, 0]
    p = -10
    distance = minkowski_distance(a, b, p)
    print(f"{a=}, {b=}, {p=}, {distance=}")  ## Expected output: a=[1, 4, 10, 0], b=[20, -3, -5, 0], p=-10, distance=-1.0

Run the minkowski_distance.py file using the following command:

python minkowski_distance.py

Verify that the output matches the expected results:

  • For the points a = [1, 0] and b = [2, 0] with p = 2, the distance should be 1.0.
  • For the points a = [4, 9, 10] and b = [2, 0, -3] with p = "INF", the distance should be 13.0.
  • For the points a = [1, 4, 10, 0] and b = [20, -3, -5, 0] with p = -10, the distance should be -1.0.
✨ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.