numpy矩阵按行归一化 按列归一化 python程序
时间: 2023-12-12 12:04:52 浏览: 197
以下是numpy矩阵按行归一化和按列归一化的Python程序:
1. 按行归一化
```python
import numpy as np
# 创建一个3x3的矩阵
x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 对每一行进行归一化
x_normed = x / np.linalg.norm(x, axis=1, keepdims=True)
# 输出归一化后的矩阵
print(x_normed)
```
输出:
```
[[0.26726124 0.53452248 0.80178373]
[0.45584231 0.56980288 0.68376346]
[0.50257071 0.57436653 0.64616235]]
```
2. 按列归一化
```python
import numpy as np
# 创建一个3x3的矩阵
x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 对每一列进行归一化
x_normed = x / np.linalg.norm(x, axis=0, keepdims=True)
# 输出归一化后的矩阵
print(x_normed)
```
输出:
```
[[0.12309149 0.20739034 0.26726124]
[0.49236596 0.51847585 0.53452248]
[0.86164043 0.82956136 0.80178373]]
```
阅读全文