l1_normalize_features.Rd
This function scales the columns of a numeric matrix such that the sum of the absolute values of each column (the L1 norm) is equal to 1. This is a common preprocessing step for feature matrices.
l1_normalize_features(features)
A matrix with the same dimensions as the input, where each column has been L1-normalized.
The function is designed to be highly efficient by using vectorized operations. It also robustly handles columns that sum to zero to prevent division-by-zero errors.
# Create a sample feature matrix
set.seed(123)
my_features <- matrix(rnorm(12, mean = 5), nrow = 4, ncol = 3)
print(my_features)
#> [,1] [,2] [,3]
#> [1,] 4.439524 5.129288 4.313147
#> [2,] 4.769823 6.715065 4.554338
#> [3,] 6.558708 5.460916 6.224082
#> [4,] 5.070508 3.734939 5.359814
#> [,1] [,2] [,3]
#> [1,] 4.4395244 5.487429 5.704929
#> [2,] 5.2325834 6.738325 5.558708
#> [3,] 3.4291247 5.575781 4.129288
#> [4,] 5.5060559 4.694612 4.261173
# Check the column sums of absolute values before normalization
print(colSums(abs(my_features)))
#> [1] 20.83856 21.04021 20.45138
#> [1] 18.60729 22.49615 19.65410
# Apply L1 normalization
normalized_features <- l1_normalize_features(my_features)
print(normalized_features)
#> [,1] [,2] [,3]
#> [1,] 0.2130437 0.2437850 0.2108976
#> [2,] 0.2288940 0.3191539 0.2226910
#> [3,] 0.3147390 0.2595467 0.3043355
#> [4,] 0.2433233 0.1775143 0.2620759
#> [,1] [,2] [,3]
#> [1,] 0.23859089 0.2439247 0.2800889
#> [2,] 0.28121151 0.2995321 0.2891398
#> [3,] 0.18429107 0.2478546 0.2151676
#> [4,] 0.29590653 0.2086886 0.2221037
# Confirm that the new column sums of absolute values are all 1
print(colSums(abs(normalized_features)))
#> [1] 1 1 1
#> [1] 1 1 1