问题描述
是否有任何干净的方法可以将 numpy 设置为全局使用 float32 值而不是 float64?
Is there any clean way of setting numpy to use float32 values instead of float64 globally?
推荐答案
我不知道.您要么需要在调用任何数组的构造函数时显式指定 dtype,要么在将数组传递给 GPU 代码之前将数组强制转换为 float32(使用 ndarray.astype 方法)(我认为这就是问题所在?).如果是你真正担心的 GPU 案例,我更喜欢后者——如果没有非常透彻地了解 numpy 广播规则和非常精心设计的代码,尝试将所有内容保持在单精度状态会变得非常烦人.
Not that I am aware of. You either need to specify the dtype explicitly when you call the constructor for any array, or cast an array to float32 (use the ndarray.astype method) before passing it to your GPU code (I take it this is what the question pertains to?). If it is the GPU case you are really worried about, I favor the latter - it can become very annoying to try and keep everything in single precision without an extremely thorough understanding of the numpy broadcasting rules and very carefully designed code.
另一种选择可能是创建自己的方法来重载标准 numpy 构造函数(如 numpy.zeros、numpy.ones、numpy.empty).这应该非常接近于将所有内容都保存在 float32 中.
Another alternative might be to create your own methods which overload the standard numpy constructors (so numpy.zeros, numpy.ones, numpy.empty). That should go pretty close to keeping everything in float32.
这篇关于Python:使 numpy 默认为 float32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!