0

Is there a way to control numpy matrix operation by single line code at the beginning or something like that? I run out of memory and want to control all my matrices to be under 'float32'. Or at least, is there a shorter way than I have to convert all matrices with .astype('float32') one by one?

Jan
  • 1,389
  • 4
  • 17
  • 43

1 Answers1

0

You could try and make a drop-in replacement module

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__()

This you would then import instead of 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])

Still a bit of work, though. And it won't work deep.

Paul Panzer
  • 51,835
  • 3
  • 54
  • 99