L2 norm in Python

The L2L_2 norm loss function, also known as the least squares error (LSE), is used to minimize the sum of the square of differences between the target value, YiY_i, and the estimated value, f(xi)f(x_i)

The mathematical representation of L2L_2-norm is:

S=i=1n(yif(xi))2S=\sum_{i=1}^n\left(y_i-f\left(x_i\right)\right)^2

As an error function, L2L_2-norm is less robust to outliers than the L1L_1-norm. An outlier causes the error value to increase to a much larger number because the difference in the actual and predicted value gets squared.

However, L2L_2-norm always provides one stable solution (unlike L1L_1-norm).

The L1L_1-norm loss function is known as the least absolute error (LAE) and ​is used to minimize the sum of absolute differences between the target value, YiY_i, and the estimated values, f(xi)f(x_i).

Code

The code to implement the L2L_2-norm is given below:

import numpy as np
actual_value = np.array([1, 2, 3])
predicted_value = np.array([1.1, 2.1, 5 ])
# take square of differences and sum them
l2_norm = np.sum(np.power((actual_value-predicted_value),2))
# take the square root of the sum of squares to obtain the L2 norm
l2_norm = np.sqrt(l2)
print(l2_norm)

Explanation

  • Lines 3 and 4: To store the heights of three people we created two Numpy arrays called actual_value and predicted_value. The predicted_value contains the heights predicted by a machine learning model.

  • Line 7: We calculate the differences between the actual_value and predicted_value arrays.

    • We used the np.power to square the differences between the elements of two arrays.

    • We use np.sum to sum the square resulting values.

  • Line 10: Finally, we take the square root of the l2_norm using np.sqrt this value shows the difference between the predicted values and actual value. This value is used to evaluate the performance of the machine learning model.

  • Line 11: We print the l2_norm.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved