|
21 | 21 | # |
22 | 22 | """Datasets to be used as part of the sklearn framework.""" |
23 | 23 |
|
| 24 | +import traceback |
| 25 | +import warnings |
24 | 26 | from typing import Iterable, Optional |
25 | 27 |
|
26 | 28 | import numpy as np |
|
34 | 36 | import cebra.solver |
35 | 37 |
|
36 | 38 |
|
| 39 | +def _ensure_writable(array: npt.NDArray) -> npt.NDArray: |
| 40 | + if not array.flags.writeable: |
| 41 | + stack = traceback.extract_stack()[-5:-1] |
| 42 | + stack_str = ''.join(traceback.format_list(stack[-4:])) |
| 43 | + |
| 44 | + warnings.warn( |
| 45 | + ("You passed a non-writable Numpy array to CEBRA. Pytorch does currently " |
| 46 | + "not support non-writable tensors. As a result, CEBRA needs to copy the " |
| 47 | + "contents of the array, which might yield unnecessary memory overhead. " |
| 48 | + "Ideally, adapt the code such that the array you pass to CEBRA is writable " |
| 49 | + "to make your code memory efficient. " |
| 50 | + "You can find more context and the rationale for this fix here: " |
| 51 | + "https://github.com/AdaptiveMotorControlLab/CEBRA/pull/289." |
| 52 | + "\n\n" |
| 53 | + "Trace:\n" + stack_str), |
| 54 | + UserWarning, |
| 55 | + stacklevel=2, |
| 56 | + ) |
| 57 | + array = array.copy() |
| 58 | + return array |
| 59 | + |
| 60 | + |
37 | 61 | class SklearnDataset(cebra.data.SingleSessionDataset): |
38 | 62 | """Dataset for wrapping array-like input/index pairs. |
39 | 63 |
|
@@ -110,6 +134,7 @@ def _parse_data(self, X: npt.NDArray): |
110 | 134 | # one sample is a conservative default here to ensure that sklearn tests |
111 | 135 | # passes with the correct error messages. |
112 | 136 | X = cebra_sklearn_utils.check_input_array(X, min_samples=2) |
| 137 | + X = _ensure_writable(X) |
113 | 138 | self.neural = torch.from_numpy(X).float().to(self.device) |
114 | 139 |
|
115 | 140 | def _parse_labels(self, labels: Optional[tuple]): |
@@ -143,6 +168,8 @@ def _parse_labels(self, labels: Optional[tuple]): |
143 | 168 | f"or lists that can be converted to arrays, but got {type(y)}" |
144 | 169 | ) |
145 | 170 |
|
| 171 | + y = _ensure_writable(y) |
| 172 | + |
146 | 173 | # Define the index as either continuous or discrete indices, depending |
147 | 174 | # on the dtype in the index array. |
148 | 175 | if cebra.helper._is_floating(y): |
|
0 commit comments