Search code examples
pythontensorflowkeras

Round values in tensor to values from a list


I am trying to round the values in a 2D tensor to the nearest value from a given list, for example:

# this is eager, but the solution must work with non eager tensors
data_to_round = tf.constant([[0.3, 0.4, 2.3], [1.4, 2.2 ,55.4]])
possible_rounding_results = [1,2,3,4,5,6]

# TODO: round `data_to_round` to nearest values from `possible_rounding_results`
# expected output: [[1, 1, 2], [1, 2 , 5]]

I was playing around with tf.math.subtract, tf.math.abs and tf.argmin in order to find the index of the minimal absolute difference between the lists using a for loop, but then I failed to combine them back to a tensor, and it didn't work at all with 2D arrays only 1D. And I am not sure if its the correct way to approach this problem at all.

Due to my total lack of experience with TensorFlow, I have no idea how to tackle such issue sorry in advance for the shallow question I am just lost.


Solution

  • If I understand you correctly, you could try something like this:

    import tensorflow as tf
    
    x = tf.constant([[0.3, 0.4, 2.5], [1.4, 2.2, 55.4]])
    possible_rounding_results = tf.constant([1,2,3,4,5,6], dtype=tf.float32)
    
    tf.clip_by_value(tf.round(x), tf.reduce_min(possible_rounding_results), tf.reduce_max(possible_rounding_results))
    
    <tf.Tensor: shape=(2, 3), dtype=float32, numpy=
    array([[1., 1., 2.],
           [1., 2., 6.]], dtype=float32)>
    

    The last value is 6 instead of 5 (as in your example) since 6 is closer to 55.4 than 5. If you meant to use tf.constant([[0.3, 0.4, 2.5], [1.4, 2.2, 5.4]]), you would get:

    <tf.Tensor: shape=(2, 3), dtype=float32, numpy=
    array([[1., 1., 2.],
           [1., 2., 5.]], dtype=float32)>