`CArray` `__getitem__` on sparse matrices changes the original array
The __getitem__
function of CArray
, if used on a sparse array, transforms the type of the wrapped sparse matrix from csr
into csc
.
Steps to reproduce
from secml.array import CArray
X = CArray([[1, 2, 3], [4, 0, 5], [6, 0, 0]], tosparse=True)
y = CArray([1, 0, 1])
print("original sparse array:", type(X._data._data))
sel_x = X[y == 1, :]
print("sparse array containing the selected data:", type(sel_x._data._data))
print("original sparse array:", type(X._data._data))
What is the expected correct behavior?
Format of the original matrix should not change after using the getitem
function.
Implementation plan
Ensure self
is in csr
format after indexing operation. Use the following snippet for CSparse.__getitem__
.
def __getitem__(self, idx):
"""Redefinition of the get (brackets) operator."""
# Check index for all other cases
idx = self._check_index(idx)
# Ready for scipy
res = self.__class__(self._data.__getitem__(idx))
# Ensure self is in csr format after indexing
self._data = self.tocsr()
return res
Modify test_getter
to check that the wrapped scipy array is in csr
format (use getformat
).