一次将所有 numpy 矩阵操作控制为类型('float32')



有没有办法通过在开头的单行代码或类似的东西来控制numpy矩阵操作?我的内存不足,想控制我所有的矩阵都在'float32'下。或者至少,有没有比我必须一一转换所有矩阵.astype('float32')更短的方法?

您可以尝试制作一个直接替换模块

import sys
class __the_module__:
def __init__(self):
import numpy as __np
import functools as __fu
self.__dict__.update(__np.__dict__)
@__fu.wraps(__np.array)
def __f(*args, dtype=__np.float32, **kwds):
return __np.array(*args, dtype=dtype, **kwds)
self.array = __f
# must do this for all functions you want to engineer
sys.modules[__name__] = __the_module__()

然后您将导入而不是 numpy

import np32 as np
# this we engineered
np.array([1.0])
# array([ 1.], dtype=float32)
# other stuff will just be passed through
np.arange(8)
# array([0, 1, 2, 3, 4, 5, 6, 7])

不过,仍然需要做一些工作。而且它不会深入工作。

最新更新