我想执行 matrix balancing在 python 。我想用 linalg.matrix_balance为了使输入矩阵成为 doubly stochastic matrix :
from scipy import linalg
import numpy as np
x = np.array([[1,2,7], [9,1,1], [1,2,10*np.pi]])
y, permscale = linalg.matrix_balance(x)
np.abs(x).sum(axis=0) / np.abs(x).sum(axis=1)
np.abs(y).sum(axis=0) / np.abs(y).sum(axis=1)
permscale
array([[ 1., 0., 0.],
[ 0., 2., 0.],
[ 0., 0., 1.]])
看起来它实际上并没有平衡矩阵的行和列。知道我该怎么做吗?
如果我这样做:y, permscale = linalg.matrix_balance(x, scale=False)
结果也没有标准化:
array([[ 1. , 2. , 7. ], [ 9. , 1. , 1. ], [ 1. , 2. , 31.41592654]])
请您参考如下方法:
您对输出的分析是正确的,但您对 matrix_balance 的考虑是错误的做。从文档中,
The balanced matrix satisfies the following equality,
B = inv(T) * A * T (matrix products)
我们可以用您的矩阵轻松验证,
>>>print(np.dot(np.dot(np.linalg.inv(permscale), x), permscale))
[[ 1. 4. 7. ]
[ 4.5 1. 0.5 ]
[ 1. 4. 31.41592654]]
这确实是 y。这意味着 matrix_balance 可以像它声称的那样工作。你声称,
It doesn't look that it actually balancing the rows and cols of the matrix. Any idea what should I do?
但这不是真的:这个修改后的矩阵的 L1 范数是平衡的,在二的一个数量级内,这样精确的数量级反射(reflect)到缩放矩阵 permscale.
您的目标是让矩阵具有双重随机性,而不是(仅仅)平衡吗?如果是这样,您可以查看例如 this project .按照此处提供的指南,我为您的数据找到了以下双随机矩阵,
>>>print(sk.fit(x))
[[ 0.1385636 0.55482644 0.30660996]
[ 0.79518122 0.17688932 0.02792947]
[ 0.06695665 0.26810303 0.66494032]]
>>>print(sk.fit(x).sum(axis=0), sk.fit(x).sum(axis=1))
[ 1.00070147 0.99981878 0.99947975] [ 1. 1. 1.]
对于大多数用例,这应该“足够接近”。
