2

I have a Tensorflow boolean vector that I need to bit-wise invert such that all the values that are 0 (False) becomes 1 (True) and vice-versa. tf.logical_not exists, but it only takes Boolean vectors. Does there exist a Tensorflow that does this on a vector of ints or floats so I don't need to recast my tensor?

pir
  • 5,513
  • 12
  • 63
  • 101

2 Answers2

5

TensorFlow doesn't include a specific operator for performing bitwise NOT, but you could simulate it with tf.bitcast() and arithmetic operations on integers. For example, the following will invert the bits in a single floating-point value:

input_value = tf.constant(37.0)

bitcast_to_int32 = tf.bitcast(input_value, tf.int32)

invert_bits = tf.constant(-1) - bitcast_to_int32

bitcast_to_float = tf.bitcast(invert_bits, tf.float32)

You can confirm that the input and output are bitwise inverses using this answer to convert the floating-point values to binary.

Community
  • 1
  • 1
mrry
  • 125,488
  • 26
  • 399
  • 400
1

The only way I see is to tf.cast the tensor to tf.bool then invoke tf.logical_not then cast back.

dtype = tensor.dtype
btensor = tf.cast(tensor, tf.bool)
not_tensor = tf.logical_not(btensor)
tensor = tf.cast(not_tensor, dtype)
jrbedard
  • 3,662
  • 5
  • 30
  • 34