NumPy 归一化矩阵
Muhammad Maisam Abbas
2021年7月4日

本教程将讨论在 Python 中规范化矩阵的方法。
使用 Python 中的 numpy.linalg.norm()
方法对矩阵进行归一化
numpy.linalg
库包含与 Python 中的线性代数相关的方法。numpy.linalg
中的 norm()
方法 计算矩阵的范数。然后我们可以使用这些范数值来对矩阵进行归一化。以下代码示例向我们展示了如何使用 numpy.linalg
库中的 norm()
方法对矩阵进行归一化。
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
norms = np.linalg.norm(matrix, axis=1)
print(matrix / norms)
输出:
[[0.4472136 0.4 ]
[1.34164079 0.8 ]]
我们首先使用 np.array()
方法以二维数组的形式创建了我们的矩阵。然后我们计算范数并将结果存储在 norms
数组中,并使用 norms = np.linalg.norm(matrix)
。最后,我们通过将 matrix
除以 norms
来规范化 matrix
并打印结果。
norm()
方法在第一个和第二个上执行相当于 np.sqrt(1**2 + 2**2)
和 np.sqrt(3**2 + 4**2)
的操作我们矩阵的行,分别。然后它为我们的 norms
数组分配两个值,它们是 [2.23606798 5.0]
。然后通过将 matrix
的每一行除以 norms
的每个元素对矩阵进行归一化。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn