How to normalise each element

·

2 min read

np.linalg.norm is a function in the NumPy library that calculates the vector norm (a measure of the length or magnitude) of the input array x. In this specific case, np.linalg.norm(x, axis=1, keepdims=True) computes the norm along the specified axis 1 (which usually corresponds to the rows) of a 2D input array x.

The parameters used are:

  1. x: The input array for which you want to compute the norm.

  2. axis=1: Specifies the axis along which the norm is computed. In a 2D array, axis 0 represents columns and axis 1 represents rows. Here, axis 1 means that the norm is computed along the rows.

  3. keepdims=True: This parameter, when set to True, retains the reduced dimensions as singleton dimensions in the output. This ensures that the output array has the same number of dimensions as the input array, which can be useful for broadcasting operations.

For example, if the input array x is:

x = [[1, 2],
     [3, 4]]

np.linalg.norm(x, axis=1, keepdims=True) would return:

[[2.23606798],
 [5.        ]]

This is because the norm of the first row [1, 2] is sqrt(1^2 + 2^2) = 2.23606798, and the norm of the second row [3, 4] is sqrt(3^2 + 4^2) = 5. The output is a 2D array with the same number of rows as the input and a single column, as specified by keepdims=True.