Python 将np.float64对象除以2将生成返回值';s数据类型np.32?
当我阅读一些Tensorflow源代码时,我发现:Python 将np.float64对象除以2将生成返回值';s数据类型np.32?,python,numpy,tensorflow,Python,Numpy,Tensorflow,当我阅读一些Tensorflow源代码时,我发现: if tf_dtype.is_floating: if spec.dtype == np.float64 and np.any(np.isinf(high - low)): # The min-max interval cannot be represented by the np.float64. This is a # problem only for np.float64, np.float32 wor
if tf_dtype.is_floating:
if spec.dtype == np.float64 and np.any(np.isinf(high - low)):
# The min-max interval cannot be represented by the np.float64. This is a
# problem only for np.float64, np.float32 works as expected.
# Spec bounds are set to read only so we can't use argumented assignment.
low = low / 2 # pylint: disable=g-no-augmented-assignment
high = high / 2 # pylint: disable=g-no-augmented-assignment
return rng.uniform(
low,
high,
size=spec.shape,
).astype(spec.dtype)
我对python不是很熟悉。上面的代码看起来很有趣,这意味着
low = low / 2
high = high / 2
将使新的低
和高
的数据类型浮动32。但是当我在python终端中尝试这个时
>>> a = np.array([2.0], dtype=np.float64)
>>> a.dtype
dtype('float64')
>>> b = a/2
>>> b.dtype
dtype('float64')
事情并非如此。代码源在第42行。有人能解释一下吗?谢谢。不用了
这看起来像是计算np.float64数组中最小值和最大值之间的间隔问题的解决方法。tensorflow代码不返回np.float32,而是计算正确的值并使用原始类型返回
此外,从您的代码片段中可以看出,您在终端上运行的代码使用纯numpy,并且不会靠近tensorflow库,因此不会从tensorflow中复制任何奇怪的行为 否。要重新缩放到不同的数据类型,可以使用标准化:
zero_to_one = np.divide(old_val/np.amax(old_val)) # normalizes to 0 - 1
new_range = zero_to_one * max_val_of_new_dtype
new_range = np.array(new_range, dtype='desired dtype')