简体   繁体   English

如何在张量流中做“四舍五入”

[英]How to do "round half up" in tensorflow

I have some question when doing tf.round(x) x=[0.4, 1.5, 2.5, -1.5, -2.5, -0.4]我在做 tf.round(x) x=[0.4, 1.5, 2.5, -1.5, -2.5, -0.4] 时有一些问题

If I want to get the ans=[0, 2, 3, -2, -3, 0] rounding half way away from zero如果我想让 ans=[0, 2, 3, -2, -3, 0] 从零四舍五入

How should I do?我应该怎么做? I've tried tf.keras.backend.round(), tf.math.round, tf.math.rint()我试过 tf.keras.backend.round(), tf.math.round, tf.math.rint()

I got similar answer in python but not in TF我在 python 中得到了类似的答案,但在 TF 中没有

>>>decimal.Decimal(101.5).quantize(decimal.Decimal('0'), rounding=decimal.ROUND_HALF_UP)
Decimal('102')
>>>decimal.Decimal(102.5).quantize(decimal.Decimal('0'), rounding=decimal.ROUND_HALF_UP)
Decimal('103')
>>>decimal.Decimal(-101.5).quantize(decimal.Decimal('0'), rounding=decimal.ROUND_HALF_UP)
Decimal('-102')
>>>decimal.Decimal(-102.5).quantize(decimal.Decimal('0'), rounding=decimal.ROUND_HALF_UP)
Decimal('-103')

Thank you谢谢

How about this ?这个怎么样 ?

x = np.array([0.4, 1.5, 2.5, -1.5, -2.5, -0.4]) 
for i, val in enumerate(x):
   if val % 1 == 0.5
       x[i] = tf.math.floor(x[i]) if val < 0 else tf.math.floor(x[i]+0.5)
   else
       x[i] = tf.math.round(x[i])
print(x)

[ 0. 2. 3. -2. [ 0. 2. 3. -2. -3. -3. 0.] 0.]

Try尝试

x=tf.constant([0.4, 1.5, 2.5, -1.5, -2.5, -0.4])
x=tf.where(x>0, tf.math.nextafter(x, np.inf), tf.math.nextafter(x, -np.inf))
x=tf.round(x)

this will round away from 0.这将从 0 舍入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM