给定一个3乘以3的数值数组
a = numpy.arange(0,27,3).reshape(3,3)
# array([[ 0, 3, 6],
# [ 9, 12, 15],
# [18, 21, 24]])为了标准化二维数组的行,我想到了
row_sums = a.sum(axis=1) # array([ 9, 36, 63])
new_matrix = numpy.zeros((3,3))
for i, (row, row_sum) in enumerate(zip(a, row_sums)):
new_matrix[i,:] = row / row_sum一定有更好的办法,不是吗?
也许可以澄清一下:通过标准化,我的意思是,每行条目的总和必须是1。但我认为这对大多数人来说都是显而易见的。
发布于 2014-03-21 06:54:36
Scikit-learn提供了一个函数normalize(),可以让您应用各种标准化。“使其和为1”称为L1范数。因此:
from sklearn.preprocessing import normalize
matrix = numpy.arange(0,27,3).reshape(3,3).astype(numpy.float64)
# array([[ 0., 3., 6.],
# [ 9., 12., 15.],
# [ 18., 21., 24.]])
normed_matrix = normalize(matrix, axis=1, norm='l1')
# [[ 0. 0.33333333 0.66666667]
# [ 0.25 0.33333333 0.41666667]
# [ 0.28571429 0.33333333 0.38095238]]现在,您的行加起来将为1。
发布于 2012-01-18 11:22:13
我想这应该行得通,
a = numpy.arange(0,27.,3).reshape(3,3)
a /= a.sum(axis=1)[:,numpy.newaxis]发布于 2014-05-11 03:13:03
如果您试图将每行归一化,使其大小为1(即,行的单位长度为1或行中每个元素的平方和为1):
import numpy as np
a = np.arange(0,27,3).reshape(3,3)
result = a / np.linalg.norm(a, axis=-1)[:, np.newaxis]
# array([[ 0. , 0.4472136 , 0.89442719],
# [ 0.42426407, 0.56568542, 0.70710678],
# [ 0.49153915, 0.57346234, 0.65538554]])验证:
np.sum( result**2, axis=-1 )
# array([ 1., 1., 1.]) https://stackoverflow.com/questions/8904694
复制相似问题