考虑以下代码:
import numpy as npA = np.array([[.8, .6], [.1, 0]])B1 = tf.keras.utils.normalize(A, axis=0, order=1)B2 = tf.keras.utils.normalize(A, axis=0, order=2)print('A:')print(A)print('B1:')print(B1)print('B2:')print(B2)
返回结果如下:
A:[[0.8 0.6] [0.1 0. ]]B1:[[0.88888889 1. ] [0.11111111 0. ]]B2:[[0.99227788 1. ] [0.12403473 0. ]]
我理解B1
是通过order=1
计算的,即A
中的每个条目除以其所在列的元素总和。例如,0.8
变为0.8/(0.8+0.1) = 0.888
。然而,我无法理解order=2
是如何产生B2
的,也找不到任何相关文档。
回答:
然而,我无法理解
order=2
是如何产生B2
的,也找不到任何相关文档。
order=1
表示L1范数,而order=2
表示L2范数。对于L2范数,你需要在对各个元素平方求和后再取平方根。具体要平方哪些元素取决于轴的选择。
Keras
A = np.array([[.8, .6], [.1, 0]])B2 = tf.keras.utils.normalize(A, axis=0, order=2)print(B2)array([[0.99227788, 1. ], [0.12403473, 0. ]])
手动计算
B2_manual = np.zeros((2,2))B2_manual[0][0] = 0.8/np.sqrt(0.8 ** 2 + 0.1 ** 2)B2_manual[1][0] = 0.1/np.sqrt(0.8 ** 2 + 0.1 ** 2)B2_manual[0][1] = 0.6/np.sqrt(0.6 ** 2 + 0 ** 2)B2_manual[1][1] = 0 /np.sqrt(0.6 ** 2 + 0 ** 2)print(B2_manual)array([[0.99227788, 1. ], [0.12403473, 0. ]])
你可以在这里查找不同类型的范数:https://en.wikipedia.org/wiki/Norm_(mathematics)工作示例:https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html