python numpy数组归一化和反归一化
时间: 2024-01-19 19:17:44 浏览: 166
以下是Python中使用numpy对数组进行归一化和反归一化的示例代码:
1. 归一化:
```python
import numpy as np
def normalize_array(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])
normalized_arr = normalize_array(arr)
print(normalized_arr) # 输出:[0. 0.25 0.5 0.75 1. ]
```
2. 反归一化:
```python
import numpy as np
def denormalize_array(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.25 , 0.5 , 0.75 , 1. ])
original_arr = np.array([1, 2, 3, 4, 5])
denormalized_arr = denormalize_array(normalized_arr, original_arr)
print(denormalized_arr) # 输出:[1. 2. 3. 4. 5.]
```
阅读全文