这是设计使然。 TensorFlow中的“真”除法(即实除法)使用_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,
}
这意味着int32 张量将被转换为float64。如果您想获得 float32 作为输出,请使用较小的 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
因此,您可能会认为,作为两个整数值的除法,您可能希望将结果与整数混合,但正如您所见,对于 32 位整数,存在 32 位浮点数会下溢的情况。
但同样,这只是猜测,更像是一种思考练习。