如何用张量流准确地四舍五入一半

How to accurately round half up with tensorflow

本文关键字:四舍五入 一半 何用张      更新时间:2023-10-16

我正在尝试将一些基于C++的代码复制到Tensorflow的Python API中,但是我遇到了一些浮点不准确的问题,尽管我已经能够找到其中之一。

通常,Tensorflow 似乎以向下舍入的方式对小数进行舍入,这意味着如果我们有一个整数,其分数值正好等于0.5,该小数的整数部分将向下舍入为零:

>>> import tensorflow as tf
>>> tf.Session().run(tf.math.round(2.5))
2.0

然而,我遇到的许多命令式编程语言都以半上舍入的方式进行舍入。其中一些编程语言是C++和Python。

事实上,考虑到Tensorflow主要是用C++,Python和Cuda C++编写的,对于他们在API中使用rounding half down方法似乎是一个奇怪的约定。


问题

有没有巧妙的方法来实现利用rounding half up方法而不是rounding half down的舍入函数?

我可以实现的最简单的函数使用tf.floormod方法:

>>> def classical_round(x): return tf.cond(tf.math.equal(tf.floormod(x, 1), tf.constant(0.5)), lambda: tf.math.ceil(x), lambda: tf.math.round(x))
...
>>> tf.Session().run(classical_round(4.5))
5.0
>>> tf.Session().run(classical_round(4.49))
4.0
>>> tf.Session().run(classical_round(4.49999999999999))
5.0
>>> tf.Session().run(classical_round(3.2))
3.0

这是足够准确的方法吗?或者可以通过使用其他TensorFlow操作来完成类似的事情吗?

研究

我只能找到与我的问题相关的这个 Github 问题,我认为他们最终添加了tf.math.rint我无法在这个问题中找到位置。

谢谢!

称银行家对C#中发生的同样的事情也没有错。 你可以尝试这样的事情:

def classical_round(x):
return tf.math.floor(x+0.5)
sess.run(classical_round(2.5)) #3.0

更多信息在这里: https://en.wikipedia.org/wiki/Rounding#Round_half_to_even