← back

Vector Norms (L1/L2/Frobenius)

#328 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

Compute the L1 norm, L2 norm, and Frobenius norm of vectors and matrices. The L1 norm is the sum of absolute values, the L2 norm is the square root of the sum of squares, and the Frobenius norm extends the L2 norm to matrices.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from typing import List, Union

def l1_norm(v: List[float]) -> float:
    return sum(abs(x) for x in v)

def l2_norm(v: List[float]) -> float:
    return sum(x * x for x in v) ** 0.5

def frobenius_norm(matrix: List[List[float]]) -> float:
    total = 0.0
    for row in matrix:
        for val in row:
            total += val * val
    return total ** 0.5

def compute_norms(
    data: Union[List[float], List[List[float]]]
) -> dict:
    # Check if it's a matrix (list of lists) or vector
    if isinstance(data[0], list):
        flat = [val for row in data for val in row]
        return {
            "l1_norm": round(l1_norm(flat), 4),
            "l2_norm": round(l2_norm(flat), 4),
            "frobenius_norm": round(frobenius_norm(data), 4)
        }
    else:
        return {
            "l1_norm": round(l1_norm(data), 4),
            "l2_norm": round(l2_norm(data), 4)
        }

Explanation

  1. L1 norm: Sum of absolute values of all elements. For a vector [1, -2, 3], L1 = |1| + |-2| + |3| = 6.
  2. L2 norm: Square root of the sum of squares. For the same vector, L2 = sqrt(1 + 4 + 9) = sqrt(14).
  3. Frobenius norm: The L2 norm generalized to matrices -- square root of the sum of all squared elements. Equivalent to treating the matrix as a flattened vector and computing its L2 norm.

Complexity

  • Time: O(n) for vectors, O(m * n) for matrices
  • Space: O(1) extra space