1

I've been working on a matrix normalization problem, stated as:

Given a matrix M, normalize its elements such that each element is divided with the corresponding column sum if element is not 0.

cwsums = np.sum(class_matrix,axis=1)
cwsums = np.reciprocal(cwsums.astype(np.float32))
cwsums[cwsums == np.inf] = 0
## this is the problem
final_matrix = np.multiply(final_matrix, cwsums)

I can construct a reciprocal mask, which I would like to apply accross the matrix, as an elementwise product, yet I can't seem to get it right. Thank you!

3
  • EDIT: what I have written seems to work, but it is slow check again, it seems to be row-wise broadcast, not columnwise. Commented May 14, 2018 at 4:41
  • You are correct, I re-edited, thanks! Commented May 14, 2018 at 4:44
  • So, you want to normalise across columns, correct? You will need axis=1, which is right. Also, my code works for me. What is the shape of your data? Commented May 14, 2018 at 4:51

1 Answer 1

2

(Addressing edited question) Looks like you meant to sum across rows using axis=0:

i = 1 / class_matrix.sum(axis=0)
i[~np.isfinite(i)] = 0

class_matrix *= i
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.