Skip to content

declearn.model.sklearn.NumpyVector

Bases: Vector

Vector subclass to store numpy.ndarray coefficients.

This Vector is designed to store a collection of named numpy arrays or scalars, enabling computations that are either applied to each and every coefficient, or imply two sets of aligned coefficients (i.e. two NumpyVector instances with similar coefficients specifications).

Use vector.coefs to access the stored coefficients.

Notes

  • A NumpyVector can be operated with either a scalar value, or another NumpyVector that has similar specifications (same coefficient names, shapes and compatible dtypes).
  • Some other Vector classes might be made compatible with NumpyVector; in that case, operating with a NumpyVector will always result in a vector of the other type. This is notably the case with TensorflowVector and TorchVector.
  • There is currently no support for GPU-acceleration with the NumpyVector class, that only handles arrays and operations placed on a CPU device.
Source code in declearn/model/sklearn/_np_vec.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
@register_vector_type(np.ndarray)
class NumpyVector(Vector):
    """Vector subclass to store numpy.ndarray coefficients.

    This Vector is designed to store a collection of named
    numpy arrays or scalars, enabling computations that are
    either applied to each and every coefficient, or imply
    two sets of aligned coefficients (i.e. two NumpyVector
    instances with similar coefficients specifications).

    Use `vector.coefs` to access the stored coefficients.

    Notes
    -----
    - A `NumpyVector` can be operated with either a scalar value,
      or another `NumpyVector` that has similar specifications
      (same coefficient names, shapes and compatible dtypes).
    - Some other `Vector` classes might be made compatible with
      `NumpyVector`; in that case, operating with a `NumpyVector`
      will always result in a vector of the other type. This is
      notably the case with `TensorflowVector` and `TorchVector`.
    - There is currently no support for GPU-acceleration with the
      `NumpyVector` class, that only handles arrays and operations
      placed on a CPU device.
    """

    @property
    def _op_add(self) -> Callable[[Any, Any], np.ndarray]:
        return np.add

    @property
    def _op_sub(self) -> Callable[[Any, Any], np.ndarray]:
        return np.subtract

    @property
    def _op_mul(self) -> Callable[[Any, Any], np.ndarray]:
        return np.multiply

    @property
    def _op_div(self) -> Callable[[Any, Any], np.ndarray]:
        return np.divide

    @property
    def _op_pow(self) -> Callable[[Any, Any], np.ndarray]:
        return np.power

    def __init__(
        self,
        coefs: Dict[str, np.ndarray],
    ) -> None:
        super().__init__(coefs)

    def __eq__(
        self,
        other: Any,
    ) -> bool:
        valid = isinstance(other, NumpyVector)
        if valid:
            valid = self.coefs.keys() == other.coefs.keys()
        if valid:
            valid = all(
                np.array_equal(self.coefs[k], other.coefs[k])
                for k in self.coefs
            )
        return valid

    def sign(
        self,
    ) -> Self:
        return self.apply_func(np.sign)

    def minimum(
        self,
        other: Union[Self, float],
    ) -> Self:
        if isinstance(other, NumpyVector):
            return self._apply_operation(other, np.minimum)
        return self.apply_func(np.minimum, other)

    def maximum(
        self,
        other: Union[Self, float],
    ) -> Self:
        if isinstance(other, Vector):
            return self._apply_operation(other, np.maximum)
        return self.apply_func(np.maximum, other)

    def sum(
        self,
    ) -> Self:
        coefs = {key: np.array(np.sum(val)) for key, val in self.coefs.items()}
        return self.__class__(coefs)

    def flatten(
        self,
    ) -> Tuple[List[float], VectorSpec]:
        v_spec = self.get_vector_specs()
        values = flatten_numpy_arrays(
            [self.coefs[name] for name in v_spec.names]
        )
        return values, v_spec

    @classmethod
    def unflatten(
        cls,
        values: List[float],
        v_spec: VectorSpec,
    ) -> Self:
        shapes = [v_spec.shapes[name] for name in v_spec.names]
        dtypes = [v_spec.dtypes[name] for name in v_spec.names]
        arrays = unflatten_numpy_arrays(values, shapes, dtypes)
        return cls(dict(zip(v_spec.names, arrays)))