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

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

谢谢


鸿蒙传说
浏览 122回答 2
2回答

手掌心

尝试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 开始舍入。

炎炎设计

这个怎么样 ?x = np.array([0.4, 1.5, 2.5, -1.5, -2.5, -0.4])&nbsp;for i, val in enumerate(x):&nbsp; &nbsp;if val % 1 == 0.5&nbsp; &nbsp; &nbsp; &nbsp;x[i] = tf.math.floor(x[i]) if val < 0 else tf.math.floor(x[i]+0.5)&nbsp; &nbsp;else&nbsp; &nbsp; &nbsp; &nbsp;x[i] = tf.math.round(x[i])print(x)[ 0. 2. 3. -2. -3. 0.]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python