python numpy多维数组归一化和反归一化
时间: 2024-01-19 11:17:44 浏览: 296
python numpy 按行归一化的实例
归一化是将数据按比例缩放,使其落入一个特定的范围。在Numpy中,可以使用以下方法对多维数组进行归一化和反归一化操作:
1. 归一化:
```python
import numpy as np
def normalize(arr):
min_val = np.min(arr)
max_val = np.max(arr)
normalized_arr = (arr - min_val) / (max_val - min_val)
return normalized_arr
# 示例
arr = np.array([[1, 2, 3], [4, 5, 6]])
normalized_arr = normalize(arr)
print(normalized_arr)
```
2. 反归一化:
```python
import numpy as np
def denormalize(arr, original_arr):
min_val = np.min(original_arr)
max_val = np.max(original_arr)
denormalized_arr = arr * (max_val - min_val) + min_val
return denormalized_arr
# 示例
normalized_arr = np.array([[0.0, 0.5, 1.0], [0.25, 0.75, 1.0]])
original_arr = np.array([[1, 2, 3], [4, 5, 6]])
denormalized_arr = denormalize(normalized_arr, original_arr)
print(denormalized_arr)
```
阅读全文