【待测】L1、L2标准化:每个元素/L1范数;每个元素/L2范数

import numpy as np
#---------------------------------#
#   l1标准化
#---------------------------------#
def l1_normalize(x, epsilon=1e-10):
    output = x / np.maximum(np.sum(np.abs(x)),epsilon)
    return output
#---------------------------------#
#   l2标准化
#---------------------------------#
def l2_normalize(x, axis=-1, epsilon=1e-10):
    output = x / np.sqrt(np.maximum(np.sum(np.square(x), axis=axis, keepdims=True),epsilon))
    return output

a = np.arange(12).reshape([1,3,4])
l1 = l1_normalize(a)
l2 = l2_normalize(a,(1,2))
print(a,"\n")
print(l1,"\n")
print(l2,"\n")
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]] 

[[[0.         0.01515152 0.03030303 0.04545455]
  [0.06060606 0.07575758 0.09090909 0.10606061]
  [0.12121212 0.13636364 0.15151515 0.16666667]]]

[[[0.         0.04445542 0.08891084 0.13336627]
  [0.17782169 0.22227711 0.26673253 0.31118796]
  [0.35564338 0.4000988  0.44455422 0.48900965]]]

猜你喜欢

转载自blog.csdn.net/nyist_yangguang/article/details/121049349
今日推荐