0

I don't understand why I got a matrix of bool values when setting a matrix < a value in Python

a3 has 12 elements and 12*0.8=9.6. How can 9.6 elements remain? Where is my mistake?

My code:

import numpy as np

keep_prod = 0.8
a3 = np.random.rand(3,4)
print("a3-before",a3)
d3 = np.random.rand(a3.shape[0],a3.shape[1])<keep_prod    ##### attention!!!
print("d3",d3)

The output:

a3-before 
[[ 0.6016695   0.733025    0.38694513  0.17916196]
 [ 0.39412193  0.22803599  0.16931667  0.30190426]
 [ 0.8822327   0.64064634  0.40085393  0.72317028]]
d3 
[[False  True  True False]
 [ True False  True  True]
 [ True  True  True  True]]
gmds
  • 19,325
  • 4
  • 32
  • 58
黄冠斌
  • 11
  • 3
  • 2
    Operator `<` is a boolean comparison operator. Naturally, it produces boolean values. What did you expect? – DYZ May 19 '19 at 03:14
  • The `d3` line creates a new random array with the same shape as `a3`, and then compares each element to `keep_prod`. It's hard to tell what you intend by the `12*0.8` calculation. – hpaulj May 19 '19 at 06:53

1 Answers1

0

It seems that you expect < 0.8 to keep 80% of the elements in the original array.

However, what really happens is that it performs that comparison elementwise, and returns an array of the same shape. In other words, d3 contains True where the corresponding element of a3 was more than or equal to 0.8, and False elsewhere.

gmds
  • 19,325
  • 4
  • 32
  • 58