如何编写NumPy数组的反归一化函数以还原原始数组?
Got it, let's break this down simply—denormalization is just reversing the steps of your normalization function. Let's start by recalling how your normalizer works, then rearrange the math to get back the original array.
Step 1: Understand the Normalization Logic
Your normalizer does two key steps for each column:
- Scales the original values to the
[0, 1]range:X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) - Rescales that
[0,1]range to your target[-1, 1]interval:X_scaled = X_std * (maxi - mini) + mini
Step 2: Derive the Denormalization Formula
To get back the original array, we just reverse these steps:
- First, convert the scaled values (from
[-1,1]) back to the[0,1]range:X_std = (scaled_X - mini) / (maxi - mini) - Then, scale that
[0,1]range back to the original data's min/max per column:original_X = X_std * (original_max - original_min) + original_min
Important note: You must save the original array's column-wise min and max values when you do the normalization—you can't get these back from the normalized array alone!
Step 3: The Denormalization Function
Here's the full denormalizer function, plus a test to verify it works with your example:
import numpy as np # Original array a = np.arange(500).reshape(100,5) # Save original column-wise min and max (critical for denormalization!) original_min = a.min(axis=0) original_max = a.max(axis=0) # Your existing normalization function def normalizer(X, mini, maxi): X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (maxi - mini) + mini return X_scaled # Normalize to [-1, 1] normalized = normalizer(a, -1, 1) # The denormalization function def denormalizer(scaled_X, original_min, original_max, mini, maxi): # Reverse the [-1,1] to [0,1] step X_std = (scaled_X - mini) / (maxi - mini) # Reverse the [0,1] to original range step original_X = X_std * (original_max - original_min) + original_min return original_X # Restore the original array restored_a = denormalizer(normalized, original_min, original_max, -1, 1) # Verify the restoration is perfect print(np.array_equal(a, restored_a)) # Output: True
Key Reminder
Always store original_min and original_max when you normalize your data—without these, you can't accurately reverse the scaling. If you're saving normalized data to disk, make sure to save these values alongside it!
内容的提问来源于stack exchange,提问作者user9703439

