简体   繁体   English

Python:将numpy默认为float32

[英]Python: Making numpy default to float32

是否有任何干净的方法来设置numpy以使用float32值而不是全局使用float64?

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?). 您需要在调用任何数组的构造函数时显式指定dtype,或者在将数组传递给GPU代码之前将数组转换为float32(使用ndarray.astype方法)(我认为这是问题所针对的? )。 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. 如果是你真正担心的GPU情况,我赞成后者 - 如果没有对numpy广播规则和非常精心设计的代码进行非常透彻的理解,尝试保持所有内容都会变得非常烦人。

Another alternative might be to create your own methods which overload the standard numpy constructors (so numpy.zeros, numpy.ones, numpy.empty). 另一种方法可能是创建自己的方法,重载标准的numpy构造函数(如numpy.zeros,numpy.ones,numpy.empty)。 That should go pretty close to keeping everything in float32. 这应该非常接近将所有内容保存在float32中。

This question showed up on the NumPy issue tracker. 这个问题出现在NumPy问题跟踪器上。 The answer is: 答案是:

There isn't, sorry. 对不起,没有。 And I'm afraid we're unlikely to add such a thing[.] 而且我担心我们不太可能添加这样的东西[。]

For each function you can overload by: 您可以通过以下方式重载每个功能:

def array(*args, **kwargs):
    kwargs.setdefault("dtype", np.float32)
    return np.array(*args, **kwargs)

As posted by njsmith on github 由njsmith在github上发布

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM