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