'tf.round() to a specified precision
tf.round(x) rounds the values of x to integer values.
Is there any way to round to, say, 3 decimal places instead?
Solution 1:[1]
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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chen Chen |
| Solution 2 | Mohamed Fathallah |
