python对数组进行L2范数归一化和z-score归一化的代码
时间: 2023-05-29 10:01:22 浏览: 408
L2范数归一化:
```python
import numpy as np
def l2_normalize(x):
norm = np.linalg.norm(x)
if norm == 0:
return x
else:
return x / norm
arr = np.array([1, 2, 3, 4, 5])
l2_norm = l2_normalize(arr)
print(l2_norm)
```
z-score归一化:
```python
import numpy as np
def z_score_normalize(x):
mean = np.mean(x)
std = np.std(x)
return (x - mean) / std
arr = np.array([1, 2, 3, 4, 5])
z_score_norm = z_score_normalize(arr)
print(z_score_norm)
```
注意,以上两种方法都是对一维数组进行归一化操作,如果是多维数组,则需要对每个维度进行操作。另外,z-score归一化只适用于数据呈正态分布的情况。
阅读全文