[英]Finding Permutation Matrix with NumPy
I am looking for the correct permutation matrix that would take matrix a and turn it into matrix b given我正在寻找正确的置换矩阵,它将矩阵 a 转换为给定的矩阵 b
a = np.array([[1,4,7,-2],[3,0,-2,-1],[-4,2,1,0],[-8,-3,-1,2]])
b = np.array([[-4,2,1,0],[3,0,-2,-1],[-8,-3,-1,2],[1,4,7,-2]])
I tried我试过
x = np.linalg.solve(a,b)
However, I know this is incorrect and it should be但是,我知道这是不正确的,应该是
np.array([[0,0,1,0],[0,1,0,0],[0,0,0,1],[1,0,0,0]])
What numpy code would deliver this matrix from the other two?什么 numpy 代码会从其他两个传递这个矩阵?
Generally, if you have some PA = B
and you want P
then you need to solve the equation for P
.一般来说,如果你有一些
PA = B
并且你想要P
那么你需要解决P
的方程式。 Matrix multiplication is not commutative, so you have to right multiply both sides by the inverse of A
.矩阵乘法不可交换,因此您必须将两边都乘以
A
的倒数。 With numpy
, the function to get the inverse of a matrix is np.linalg.inv()
.使用
numpy
,获得矩阵逆的 function 是np.linalg.inv()
。
Using the matrix multiplication operator @
, you can right-multiply with b
to get P
, taking note that you will end up with floating point precision errors:使用矩阵乘法运算符
@
,您可以与b
右乘得到P
,注意您最终会遇到浮点精度错误:
In [4]: b @ np.linalg.inv(a)
Out[4]:
array([[-1.38777878e-16, -3.05311332e-16, 1.00000000e+00,
-1.31838984e-16],
[ 0.00000000e+00, 1.00000000e+00, 6.93889390e-17,
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, -1.11022302e-16,
1.00000000e+00],
[ 1.00000000e+00, -4.44089210e-16, 5.55111512e-17,
0.00000000e+00]])
As @Mad Physicist points out, you can compare this matrix with > 0.5
to convert it to a boolean matrix:正如@Mad Physicist 指出的那样,您可以将此矩阵与
> 0.5
进行比较以将其转换为 boolean 矩阵:
In [7]: bool_P = (b @ np.linalg.inv(a)) > 0.5
In [8]: bool_P @ a
Out[8]:
array([[-4, 2, 1, 0],
[ 3, 0, -2, -1],
[-8, -3, -1, 2],
[ 1, 4, 7, -2]])
In [9]: bool_P @ a == b # our original equation, PA = B
Out[9]:
array([[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True]])
solve
computes x
in the equation Ax = B
. solve
计算方程Ax = B
中的x
。 You can use it, but the arguments have to match.你可以使用它,但 arguments 必须匹配。
Your equation is XA = B
.你的等式是
XA = B
。 You can take the transpose of both sides to get A T X T = B T
, which has the correct form.您可以对两边进行转置以获得
A T X T = B T
,它具有正确的形式。 So you can get the result from所以你可以得到结果
np.linalg.solve(A.T, B.T).T
To get a boolean result that's guaranteed to be zeros and ones, you can apply a threshold:要获得保证为零和一的 boolean 结果,您可以应用阈值:
np.linalg.solve(A.T, B.T).T > 0.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.