2

Currently my code looks like this:

class GradientDescent:

    def __init__(self, shape, log_space=False):
        """
        * log_space puts the weights in log space automatically.
        """
        super().__init__()
        self.w = np.ones(shape)

        if log_space:
            self.true_weight_proxy = GradientDescent.LogTrueWeightProxy(self)
        else:
            self.true_weight_proxy = self.w

    class LogTrueWeightProxy:

        def __init__(self, gradient_descent):
            self.gradient_descent = gradient_descent

        @property
        def shape(self):
            return self.gradient_descent.w.shape

        def __getitem__(self, indices):
            return np.exp(self.gradient_descent.w[indices])

        def __setitem__(self, indices, new_weight):
            self.gradient_descent.w[indices] = np.log(new_weight)

        def __array__(self, dtype=None):
            retval = np.exp(self.gradient_descent.w)
            if dtype is not None:
                retval = retval.astype(dtype, copy=False)
            return retval

    @property
    def true_weight(self):
        return self.true_weight_proxy

This allows me to do things like:

weight = x.true_weight
weight = x.true_weight[2, 3]
x.true_weight[2, 3] = new_weight

If the object's log_space flag is on, the weights are put into log space.

My problem is that I don't like having to expose the numpy methods one by one to access e.g. x.true_weight.shape, and inheritance is inappropriate for a proxy object. Is there a numpy mixin class the provides methods and properties like dtype, shape, etc. so that my proxy object will appear to be a numpy array for all purposes.

Neil G
  • 32,138
  • 39
  • 156
  • 257
  • 1
    What are the `self.weight` and `true_weights`? arrays? Please give an example of how you'd like to use it – shx2 Mar 21 '15 at 13:20
  • @shx2: I've updated the question with a partial solution. Please let me know if it's not clear. – Neil G Mar 21 '15 at 13:42

0 Answers0