Home > database >  applying a mask to matrices gives different objects in numpy
applying a mask to matrices gives different objects in numpy

Time:03-22

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?

CodePudding user response:

M is a np.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 using asarray ravel)

X[Omega] = M[Omega].A1

Output:

>>> X
array([[ 1.        ,  1.        ,  2.        ],
       [ 0.        ,  1.        ,  1.        ],
       [ 1.        ,  2.        , -0.00793191],
       [ 1.        ,  0.42895392,  0.05560748]])
  • Related