簡體   English   中英

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

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

我在做 tf.round(x) x=[0.4, 1.5, 2.5, -1.5, -2.5, -0.4] 時有一些問題

如果我想讓 ans=[0, 2, 3, -2, -3, 0] 從零四舍五入

我應該怎么做? 我試過 tf.keras.backend.round(), tf.math.round, tf.math.rint()

我在 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')

謝謝

這個怎么樣 ?

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. -3. 0.]

嘗試

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)

這將從 0 舍入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM