基于scikit-learn求向量/矩阵的L1范数和L2范数

示例代码如下:

from sklearn import preprocessing 
import numpy as np

X = [[ 1., -1.,  2.],
     [ 2.,  0.,  0.],
     [ 0.,  1., -1.]]

X_l1 = preprocessing.normalize(X, norm='l1')
X_l1
# array([[ 0.25, -0.25,  0.5 ],
#        [ 1.  ,  0.  ,  0.  ],
#        [ 0.  ,  0.5 , -0.5 ]])


X_l2 = preprocessing.normalize(X, norm='l2')
X_l2
# array([[ 0.40824829, -0.40824829,  0.81649658],
#        [ 1.        ,  0.        ,  0.        ],
#        [ 0.        ,  0.70710678, -0.70710678]])

np.sqrt(np.sum(X_l2**2, axis=1)) # verify that L2-norm is indeed 1
# array([ 1.,  1.,  1.])

’参考链接:python - norm parameters in sklearn.preprocessing.normalize - Stack Overflow

posted @ 2022-11-13 22:35  dlhl  阅读(48)  评论(0)    收藏  举报