""" ============================================================= NORMALIZACJA OBSERWACJI – Normalizer (L1, L2, Max) Materiał dydaktyczny ============================================================= Uwaga: Normalizer działa na WIERSZACH (obserwacjach), a nie na kolumnach (cechach) jak MinMaxScaler. """ import numpy as np from sklearn.preprocessing import Normalizer # ── Macierz cech (każdy wiersz = jedna obserwacja) ──────────────────────────── features = np.array([[ 0.5, 0.5], [ 1.1, 3.4], [ 1.5, 20.2], [1.63, 34.4], [10.9, 3.3]]) print("Oryginalna macierz cech:") print(features) # ── Normalizacja L2 (euklidesowa) ───────────────────────────────────────────── normalizer_l2 = Normalizer(norm="l2") features_l2 = normalizer_l2.transform(features) print("\nPo normalizacji L2 (każdy wiersz ma długość = 1):") print(features_l2) # Weryfikacja: norma każdego wiersza powinna wynosić 1 normy_l2 = np.linalg.norm(features_l2, axis=1) print("\nNormy L2 wierszy (powinny = 1.0):", np.round(normy_l2, 6)) # ── Normalizacja L1 (Manhattan) ─────────────────────────────────────────────── normalizer_l1 = Normalizer(norm="l1") features_l1 = normalizer_l1.transform(features) print("\nPo normalizacji L1 (suma wartości bezwzgl. w wierszu = 1):") print(features_l1) normy_l1 = np.abs(features_l1).sum(axis=1) print("\nSumy |x| L1 wierszy (powinny = 1.0):", np.round(normy_l1, 6)) # ── Normalizacja Max (Chebyshev) ────────────────────────────────────────────── normalizer_max = Normalizer(norm="max") features_max = normalizer_max.transform(features) print("\nPo normalizacji Max (max wartość w wierszu = 1):") print(features_max) # ── Tabela porównawcza ──────────────────────────────────────────────────────── print("\n{:<20} {:>10} {:>10} {:>10} {:>10}".format( "Obserwacja", "c1 oryg.", "c2 oryg.", "c1 L2", "c2 L2")) print("-" * 60) for i in range(len(features)): print("{:<20} {:>10.3f} {:>10.3f} {:>10.6f} {:>10.6f}".format( f"obs[{i}]", features[i, 0], features[i, 1], features_l2[i, 0], features_l2[i, 1])) # ── Wyjaśnienie wzorów ──────────────────────────────────────────────────────── print(""" Stosowane wzory: L2 (domyślna): x' = x / sqrt(x1² + x2² + ... + xn²) L1 : x' = x / (|x1| + |x2| + ... + |xn|) Max : x' = x / max(|x1|, |x2|, ..., |xn|) """)