Hi everyone,
Is it possible to use boolean indexing in Keras (with TF backend) ?
Here is a little script to see what I want to do, with the errors I get:
import numpy as np
import keras
from keras import backend as K
print(keras.__version__,K.tensorflow_backend.tf.__version__)
# 1.2.0 0.11.0rc2
m = np.random.randn(10,10)
b = np.random.uniform(size=(10,10))
M = K.variable(m)
B = K.variable(B)
boolean_mask = K.greater(B,0.5)
# This works fine, in numpy
np_bool = M.eval(session=K.get_session())[boolean_mask.eval(session=K.get_session())]
# But this does not
keras_bool = M[boolean_mask]
I am looking for something that is similar to tf.boolean_mask.
Thank you in advance !
This might be an workaround:
Tested under tf.
treshold = 0.5
mask = Lambda(lambda x:backend.greater(x, treshold)(some_layer)
mask = Lambda(lambda x:backend.cast(x, 'float32'))(mask)
masked_thing = Lambda(lambda x: x * mask)(thing)
This issue has been automatically marked as stale because it has not had recent activity. It will be closed after 30 days if no further activity occurs, but feel free to re-open a closed issue if needed.
this is a very desirable feature to have when writing custom loss functions.
The solution by @MarkSeygan might works if loss then aggregated by sum, but breaks if the aggregation is performed with mean.
I also hope this feature can be added to backend, so that some tricks can be done neatly when writing custom loss without manually multiplying with casted value as mentioned by https://github.com/keras-team/keras/issues/4976#issuecomment-296207349.
See tf.boolean_mask
Most helpful comment
this is a very desirable feature to have when writing custom loss functions.
The solution by @MarkSeygan might works if loss then aggregated by sum, but breaks if the aggregation is performed with mean.