对矩阵应用掩码会在 numpy 中给出不同的对象
我主要使用 MATLAB,并且正在将一些编写的代码转换为 Python。我遇到了一个问题,我有一个布尔掩码,我称之为 Omega,当我将掩码应用于不同的 m × n 矩阵时,我称之为 X 和 MI 得到不同的对象。这是我的代码
import numpy as np
from numpy import linalg as LA
m = 4
n = 3
r = 2
A = np.matrix('1 0; 0 1; 1 1;1 2')
B = np.matrix('1 1 2; 0 1 1')
M = A @ B
Omega = np.matrix('1 1 1;1 1 1;1 1 0;1 0 0',dtype=bool) #mask
X = np.copy(M)
X[~Omega] = 0
U, S, Vh = LA.svd(X) #singular value decompostion of X
Sigma = np.zeros((m,n))
np.fill_diagonal(Sigma,S)
X = U[:,0:r] @ Sigma[0:r,0:r] @ Vh[0:r,:]
print(X[Omega])
print(M[Omega])
X[Omega] = M[Omega]
,我在最后一行收到错误“NumPy 布尔数组索引分配需要 0 或 1 维输入,输入有 2 维”。然而,问题似乎是 X[Omega] 和 M[Omega] 是不同的对象,因为 X[Omega] 周围有单括号,M[Omega] 周围有双括号。特别是,打印命令打印出
[0.78935751 1.12034437 2.01560085 0.4845614 0.72316014 0.96411184 1.10709648 1.93881358 0.24918864]
[[1 1 2 0 1 1 1 2 1]]
How can I fix this?
I've mostly worked with MATLAB, and I am converting some of my code that I have written into Python. I am running into an issue where I have a boolean mask that I am calling Omega, and when I apply the mask to different m by n matrices that I call X and M I get different objects. Here is my code
import numpy as np
from numpy import linalg as LA
m = 4
n = 3
r = 2
A = np.matrix('1 0; 0 1; 1 1;1 2')
B = np.matrix('1 1 2; 0 1 1')
M = A @ B
Omega = np.matrix('1 1 1;1 1 1;1 1 0;1 0 0',dtype=bool) #mask
X = np.copy(M)
X[~Omega] = 0
U, S, Vh = LA.svd(X) #singular value decompostion of X
Sigma = np.zeros((m,n))
np.fill_diagonal(Sigma,S)
X = U[:,0:r] @ Sigma[0:r,0:r] @ Vh[0:r,:]
print(X[Omega])
print(M[Omega])
X[Omega] = M[Omega]
I get the error "NumPy boolean array indexing assignment requires a 0 or 1-dimensional input, input has 2 dimensions" on the last line. However, the issue seems to be that X[Omega] and M[Omega] are different objects, in the sense that there are single brackets around X[Omega] and double brackets around M[Omega]. In particular, the print commands print out
[0.78935751 1.12034437 2.01560085 0.4845614 0.72316014 0.96411184 1.10709648 1.93881358 0.24918864]
[[1 1 2 0 1 1 1 2 1]]
How can I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
M
是一个np.matrix
,它始终是二维的(因此它具有二维)。正如错误消息所示,在分配给用布尔掩码屏蔽的数组时(这就是您正在做的事情),您只能使用 0 或 1 维数组。相反,首先将
M
转换为数组(如 @hpaulj 指出,比使用更好asarray
+ravel
)输出:
M
is anp.matrix
, which are always 2-D (so it has two dimensions). As the error message indicates, you can only use a 0- or 1-D array when assigning to an array masked with a boolean mask (which is what you're doing).Instead, convert
M
to an array first (which, as @hpaulj pointed out, is better than usingasarray
+ravel
)Output: