使用numpy对多维数组沿着行或列进行标准化的方法

我们在此用到了python的广播机制(Broadcasting):
下面展示一些 内联代码片

第一种实现代码如下
import numpy
matrix = numpy.arange(0,27,3).reshape(3,3).astype(numpy.float64)
row_sums = ormed_matrix.sum(axis=1) 
#axis=1代表对每一行进行标准化,为0则是对列
new_matrix = ormed_matrix / row_sums[:, numpy.newaxis]
new_matrix


array([[0.        , 0.33333333, 0.66666667],
       [0.25      , 0.33333333, 0.41666667],
       [0.28571429, 0.33333333, 0.38095238]])

第二种方式
from sklearn.preprocessing import normalize
import numpy
matrix = numpy.arange(0,27,3).reshape(3,3).astype(numpy.float64)
ormed_matrix = normalize(matrix, axis=1, norm='l1')
#axis为1对行标准化,可以看出下面输出的每一行之和为1
ormed_matrix


array([[0.        , 0.33333333, 0.66666667],
       [0.25      , 0.33333333, 0.41666667],
       [0.28571429, 0.33333333, 0.38095238]])

你可能感兴趣的:(numpy,标准化)