Norm of a Vector in Python - Steps for Calculation With Examples

The norm of a vector refers to the length or the magnitude of a vector. There are different ways to calculate the length. The norm of a vector is a non-negative value. In this tutorial, we will learn how to calculate the different types of norms of a vector.

Norm of a vector x is denoted as: ‖x

The norm of a vector is a measure of its distance from the origin in the vector space.

To calculate the norm, you can either use Numpy or Scipy. Both offer a similar function to calculate the norm.

In this tutorial we will look at two types of norms that are most common in the field of machine learning.

These are :

How to Calculate the L1 Norm of a Vector?

L1 Norm of a vector is also known as the Manhattan distance or Taxicab norm. The notation for L1 norm of a vector x is ‖x1.

To calculate the norm, you need to take the sum of the absolute vector values.

Let’s take an example to understand this:

For the array above, the L1 norm is going to be:

Let’s take another example:

The L1 norm of this array is :

The L1 norm for both the vectors is the same as we consider absolute values while computing it.

Python Implementation of L1 norm

Let’s see how can we calculate L1 norm of a vector in Python.

Using Numpy

The Python code for calculating L1 norm using Numpy is as follows :

Output :

Let’s try calculating it for the array with negative entries in our example above.

Output :

Using Scipy

To calculate L1 using Scipy is not very different from the implementation above.

The code for same is:

Output :

The code is exactly similar to the Numpy one.

How to Calculate L2 Norm of a Vector?

The notation for the L2 norm of a vector x is ‖x2.

To calculate the L2 norm of a vector, take the square root of the sum of the squared vector values.

Another name for L2 norm of a vector is Euclidean distance. This is often used for calculating the error in machine learning models.

The Root Mean square error is the Euclidean distance between the actual output of the model and the expected output.

The goal of a machine learning model is to reduce this error.

Let’s consider an example to understand it.

The L2 norm for the above is :

L2 norm is always a positive quantity since we are squaring the values before adding them.

Python Implementation

The Python implementation is as follows :

Output :

Here we can see that by default the norm method returns the L2 norm.


This tutorial was about calculating L1 and L2 norms in Python. We used Numpy and Scipy to calculate the two norms. Hope you had fun learning with us!

By admin

Leave a Reply