Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

applying a mask to matrices gives different objects in numpy

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading