numpy 指定 astype 为 float32,为何结果仍为 float64?
在图像预处理函数中,astype 被指定为 float32,但输出结果的 dtype 却为 float64。这种现象的原因在于后续计算的影响。
在图像预处理过程中,astype(np.float32) 将原始图像数据(通常是 uint8)转换为 float32 格式。然而,后续的 image = (image - mean) / std 计算涉及 mean 和 std 数组,它们都是 float64 类型。
当 float32 和 float64 数组进行运算时,结果将自动提升为 float64。这是因为 float64 具有更高的精度,可以容纳更多的小数位。因此,image 数组的结果 dtype 变成 float64。
为了使 image 数组保持 float32 类型,一种解决方案是将 mean 和 std 数组也转换成 float32。例如:
mean = np.array([0.485, 0.456, 0.406]).astype(np.float32).reshape((3, 1, 1)) std = np.array([0.229, 0.224, 0.225]).astype(np.float32).reshape((3, 1, 1))
通过这种方式,整个计算过程都保持在 float32 精度下,最终 image 数组的 dtype 也将为 float32。
以上就是Numpy astype(np.float32)后为何结果仍为 float64?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号