15

tf.round(x) rounds the values of x to integer values.

Is there any way to round to, say, 3 decimal places instead?

KOB
  • 4,084
  • 9
  • 44
  • 88

2 Answers2

11

You can do it easily like that, if you don't risk reaching too high numbers:

def my_tf_round(x, decimals = 0):
    multiplier = tf.constant(10**decimals, dtype=x.dtype)
    return tf.round(x * multiplier) / multiplier

Mention: The value of x * multiplier should not exceed 2^32. So using the above method, should not rounds too high numbers.

Chen Chen
  • 3
  • 2
gdelab
  • 6,124
  • 2
  • 26
  • 59
1

The Solution of gdelab is very Good moving the required decimal point numbers to left for "." then get them later like "0.78969 * 100" will move 78.969 "2 numbers" then Tensorflow round will make it 78 then you divide it by 100 again making it 0.78 it smart one There is another workaround I would like to share for the Community.

You Can just use the NumPy round method by taking the NumPy matrix or vector then applying the method then convert the result to tensor again

#Creating Tensor
x=tf.random.normal((3,3),mean=0,stddev=1)
x=tf.cast(x,tf.float64)
x



#Grabing the Numpy array from tensor
x.numpy()


#use the numpy round method then convert the result to tensor again
value=np.round(x.numpy(),3)
Result=tf.convert_to_tensor(temp,dtype=tf.float64)
Result
Mohamed Fathallah
  • 1,274
  • 1
  • 15
  • 17