python - 标准化矩阵python的行

标签 python numpy python-2.x

给定一个 python 中的二维数组,我想用以下规范对每一行进行归一化:

  • 标准 1:L_1
  • 标准 2:L_2
  • 规范信息:L_Inf

我已经开始这段代码:

from numpy import linalg as LA
X = np.array([[1, 2, 3, 6],
              [4, 5, 6, 5],
              [1, 2, 5, 5],
              [4, 5,10,25],
              [5, 2,10,25]])

print X.shape
x = np.array([LA.norm(v,ord=1) for v in X])
print x

输出:

   (5, 4)             # array dimension
   [12 20 13 44 42]   # L1 on each Row

我如何修改代码,以便在不使用 LOOP 的情况下直接对矩阵的行进行归一化? (给定上述标准值)

我试过了:

 l1 = X.sum(axis=1)

 print l1
 print X/l1.reshape(5,1)

 [12 20 13 44 42]
 [[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

但输出为零。

最佳答案

这是 L₁ 范数:

>>> np.abs(X).sum(axis=1)
array([12, 20, 13, 44, 42])

这是 L₂ 范数:

>>> np.sqrt((X * X).sum(axis=1))
array([  7.07106781,  10.09950494,   7.41619849,  27.67670501,  27.45906044])

这是 L∞ 范数:

>>> np.abs(X).max(axis=1)
array([ 6,  6,  5, 25, 25])

要规范化行,只需除以范数即可。例如,使用 L₂ 归一化:

>>> l2norm = np.sqrt((X * X).sum(axis=1))
>>> X / l2norm.reshape(5,1)
array([[ 0.14142136,  0.28284271,  0.42426407,  0.84852814],
       [ 0.39605902,  0.49507377,  0.59408853,  0.49507377],
       [ 0.13483997,  0.26967994,  0.67419986,  0.67419986],
       [ 0.14452587,  0.18065734,  0.36131469,  0.90328672],
       [ 0.18208926,  0.0728357 ,  0.36417852,  0.9104463 ]])
>>> np.sqrt((_ * _).sum(axis=1))
array([ 1.,  1.,  1.,  1.,  1.])

更直接的是 numpy.linalg 中的 norm 方法,如果你有的话:

>>> from numpy.linalg import norm
>>> norm(X, axis=1, ord=1)  # L-1 norm
array([12, 20, 13, 44, 42])
>>> norm(X, axis=1, ord=2)  # L-2 norm
array([  7.07106781,  10.09950494,   7.41619849,  27.67670501,  27.45906044])
>>> norm(X, axis=1, ord=np.inf)  # L-∞ norm
array([ 6,  6,  5, 25, 25])

(OP 编辑​​后):您看到了零值,因为 / 是 Python 2.x 中的整数除法。要么升级到 Python 3,要么将 dtype 更改为 float 以避免整数除法:

>>> linfnorm = norm(X, axis=1, ord=np.inf)
>>> X.astype(np.float) / linfnorm[:,None]
array([[ 0.16666667,  0.33333333,  0.5       ,  1.        ],
       [ 0.66666667,  0.83333333,  1.        ,  0.83333333],
       [ 0.2       ,  0.4       ,  1.        ,  1.        ],
       [ 0.16      ,  0.2       ,  0.4       ,  1.        ],
       [ 0.2       ,  0.08      ,  0.4       ,  1.        ]])

关于python - 标准化矩阵python的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36267936/

相关文章:

python - 如何获取纯文本 Django 错误页面

python - 如何将键值对的 JSON 数组转换为 JSON 对象?

python - SciPy 1D 高斯拟合

python - 将数据列添加到只有一行的 numpy rec 数组中

javascript - 使用 Python 抓取网页的 JavaScript 页面

python - 防止函数成为 Python 2 中的实例方法

python - 为什么我的 django 元素中的 css 不呈现?

python - 在 Python 中可视化 RDFLIB 图

python - 使用 Python 将索引设置为 csv 文件中重复行值的组

python - 属性错误: 'function' object has no attribute 'my_args'