Olf*_*way 5 implicit-conversion tensorflow
我将 int32 类型的张量除以 int32 类型的张量,结果是 float64。我找不到关于为什么会发生这种情况的答案,或者 Tensorflow 如何执行此操作背后是否存在隐含规则。我还没有为任何张量明确定义 dtype,但我已经检查了所有张量,并且在除法之后它们都没有 64 位类型。
我尝试过使用不同的除法公式,例如 tf.divide,都给出相同的结果。
我的代码如下所示:
a_cdf = a / tf.size(a)
Run Code Online (Sandbox Code Playgroud)
具有 tf.int32 类型。
我想要得到的是 float32 形式的结果,这样我就可以编写我的函数而无需显式转换。
这是设计使然。TensorFlow 中的“真”除法(即实数除法)使用 a_TRUEDIV_TABLE
来指定每种类型的转换规则,当前内容为:
# Conversion table for __truediv__. None entries mean no conversion required.
_TRUEDIV_TABLE = {
dtypes.uint8: dtypes.float32,
dtypes.int8: dtypes.float32,
dtypes.uint16: dtypes.float32,
dtypes.int16: dtypes.float32,
dtypes.int32: dtypes.float64,
dtypes.int64: dtypes.float64,
dtypes.bfloat16: None,
dtypes.float16: None,
dtypes.float32: None,
dtypes.float64: None,
dtypes.complex64: None,
dtypes.complex128: None,
}
Run Code Online (Sandbox Code Playgroud)
这意味着int32
张量将转换为float64
. 如果您想获得 afloat32
作为输出,请使用较小的 int 类型或将输入转换为float32
.
这样做的理由是另一回事。如果我不得不猜测,一方面我会说如果您使用 8 位或 16 位整数,您可能会担心内存,因此较小的结果类型是有意义的。而且,您还可以给出以下论点:
import numpy as np
# Compute smallest positive divisions with 16 and 32 bits
smallest_16bit_fraction = 1 / ((1 << 16) - 1)
smallest_32bit_fraction = 1 / (-(1 << 31)) # 31 bits because int32 is signed
# Compute one plus the smallest fractions with 32 and 64 bit floats
print(np.float32(1) + np.float32(smallest_16bit_fraction))
# 1.0000153
print(np.float64(1) + np.float64(smallest_16bit_fraction))
# 1.0000152590218967
print(np.float32(1) + np.float32(smallest_32bit_fraction))
# 1.0
print(np.float64(1) + np.float64(smallest_32bit_fraction))
# 0.9999999995343387
Run Code Online (Sandbox Code Playgroud)
因此,您可能会认为,作为两个整数值的除法,您可能希望将结果与整数混合,但正如您所看到的 32 位整数一样,在某些情况下 32 位浮点数会下溢。
但同样,这只是猜测,更多的是一种思考练习。
归档时间: |
|
查看次数: |
2170 次 |
最近记录: |