Repository navigation
Enable config setting sparse_interface to control sparray and spmatrix creation - #31177
Conversation
|
Another note: We can work around it for now with e.g. The recent features for sparse by version are:
This info might help us decide when to support which versions. I think the construction functions are all that is currently needed. If/when we start using indexing code for both sparse and dense, we will likely want 1.15. If/when we want nD sparse we will need v1.16, and broadcasting binary operations in v1.17. But for now, 1.8 leaves out only construction functions from current code. |
e2b7d8b to
251e2e2
Compare
|
It sounds like the community has decided to convert to SciPy sparray using the config parameter. This PR is a start toward that. I've removed the "Draft status" from the PR. I am ready to implement this approach in other parts of the library. I have two questions:
|
thomasjpfan
left a comment
There was a problem hiding this comment.
Yup, this is basically what I had in mind.
5e3d3cd to
511de76
Compare
|
I've updated the name and example code -- and I added a commit that implements (with a These changes are largely orthogonal to the return sparse interface issue we've been focusing on here. But it is a needed step that would be easier to get feedback on here before this gets any bigger. If you'd prefer this in a different PR let me know. And if it'd be good to put further changes in a separate PR let me know. The further changes are mostly switching Do my choices for function names that bridge the old versions of SciPy look ok? |
8b58511 to
a802f12
Compare
05da23c to
6fbaae6
Compare
8994094 to
220e7f1
Compare
5d190f2 to
2d71b2c
Compare
|
Okay, I think this is finally ready for review. I've implemented a config to determine the type of sparse matrix to return (sparray or spmatrix). Both kinds can be used for sparse inputs. New helper functions in
New Scipy Version bool flags to ease indexing code that depends on SciPy version (mostly index that make 1D arrays):
All internal constructors are switched to If you want me to separate this into smaller PRs, let me know. CC: @thomasjpfan , @lorentzenchr, @jjerphan, #26418 |
|
@scikit-learn/core-devs ping for visibility |
adrinjalali
left a comment
There was a problem hiding this comment.
Seems pretty straightforward to me.
| - `"sparray"`: Return sparse as SciPy sparse array | ||
| - `"spmatrix"`: Return sparse as SciPy sparse matrix |
There was a problem hiding this comment.
are we changing this default at some point? Should we introducing a deprecation cycle at the same time?
There was a problem hiding this comment.
I propose to start a deprecation in a different PR because we first need to find a consensus as per when we do that.
2d71b2c to
1d724ec
Compare
|
I'm going to resolve conflicts with main once again here. I think we need to decide what's going to happen with this PR. We are about midway between releases so if we wait much longer we won't have time to let people try it on the pre-release level. We are close to completion, but I don't think we have a way to know how many changes are left. I've tried hard to find everything -- and I like the spirit of the 80-20 effort approach that @lorentzenchr put forward. We get rid of most of the problems here and we pay close attention after it is merged and respond fully and quickly when issues arise. I think we have experience with the types of problems and how to approach fixing them. I can offer some intensive attention over the next 2-3 months on Issues and PRs that tag me. And again after the next release. I can also offer attention over the next 3 years. Beyond that it is hard to forecast. :) I'm hearing conflicting suggestions, so I'd like to ask some questions here about what needs to be done to this before it gets merged.
Can you guys put this PR on the agenda for a meeting and hopefully decide on a path forward for it? I'll resolve conflicts and merge with main in the meantime. Thanks!! |
|
@scikit-learn/core-devs @thomasjpfan @lesteve @adrinjalali I intent to merge this by the end of February because it is a pain to keep this PR up to date. If you disagree on the approach of this PR, please tell so. |
thomasjpfan
left a comment
There was a problem hiding this comment.
I'm +1 on moving forward with this before the next release. High level thoughts:
- I suspect there will be unexpected side effects from this PR that we will uncover when it's released.
- It'll be easy to miss the
_align_api_if_sparsefor future functions.
| if not PARALLEL_RUN_AVAILABLE: | ||
| parser.addini("thread_unsafe_fixtures", "list of stuff") | ||
| parser.addoption( | ||
| "--check_spmatrix", |
There was a problem hiding this comment.
Is the plan to run this in CI at some point?
There was a problem hiding this comment.
@adrinjalali requested a CI run dedicated to this kind of thing. It is currently set up to work at the command line. It could be put into CI in a follow-up PR. I don't think it should be in this PR.
| assert not hasattr(clustering, "distances_") | ||
|
|
||
|
|
||
| @pytest.mark.no_check_spmatrix # pickle breaks check_spmatrix |
There was a problem hiding this comment.
How will a contributor know to add the no_check_spmatrix marker?
There was a problem hiding this comment.
They will need to add the no_check_spmatrix mark for tests that require the on-disk code files. This currently only occurs for tests using pickle on spmatrix objects and tests that look for the __module__ attribute of the class.
That is hard to teach a contributor -- and it is too detailed to include in a contributor guide. I also don't think we can anticipate all the ways they could use an in-memory coded class as if it is written in a file in the repo.
I guess that's a reason for not doing this kind of test -- that is, we could remove the code in this PR's conftest.py. I'd be fine with that.
Even more than a contributor not knowing how to handle it, will the reviewers remember how to handle it? If they remember that spmatrix stuff should tag @dschult that'd be enough, but I'm not sure all reviewers would know that.
Without this check_spmatrix stuff, contributors need to know that their code should work for sparray and spmatrix (so they can't use * when they mean @). And shapes might be 1D (or nD) with sparray and always 2D with spmatrix. More importantly reviewers will need to know that any sparse code coming in will need to work for both spmatrix and sparray -- at least until spmatrix is no longer supported.
Thanks a lot for your continued efforts on this @dschult 🙏. I have added this point to the monthly meeting today. |
|
So this PR was mentioned at the meeting, the summary was:
|
|
Sounds great -- I merged with main. I'll watch for review questions -- :) |
Hi @lesteve! Just a quick ping to remind you about the detailed review of this PR. Happy March! |
There was a problem hiding this comment.
Here is the promised detailed review (better late than never 😅)! Below are the comments that may make sense to tackle before this PR is merged.
I may have a few other comments, but they can likely be done in follow-up PRs. The hope would be to merge this PR and iterate if follow-up PRs if needed.
| # reorder categories in lexicographic order | ||
| order = np.argsort(categories) | ||
| categories = categories[order] | ||
| y = sp.csr_matrix(y[:, order]) |
There was a problem hiding this comment.
I would use _align_api_if_sparse on y as well since we are using it on X.
| prefer_skip_nested_validation=True, | ||
| ) | ||
| def img_to_graph(img, *, mask=None, return_as=sparse.coo_matrix, dtype=None): | ||
| def img_to_graph(img, *, mask=None, return_as=sparse.coo_array, dtype=None): |
There was a problem hiding this comment.
I originally thought this was changing the output type of a public function, which would have been a problem. Actually it's not the case, since this calls _to_graph which uses the config.
This is potentially a teeny bit misleading if for example you pass return_as=sparse.csc_array and it gets overriden by the config, and you get a csc_matrix out.
My gut feeling is that it is fine because it is a multi-level edge case:
- this is not really a core functionality of scikit-learn
- probably most users use the default
return_asvalue, which still has the same behaviour (returns acoo_matrix) - even then most users will not care about the difference between sparray and spmatrix
| # Fundamental code to switch to sparray in any format | ||
| return getattr(sp.sparse, X.format + "_array")(X) | ||
| return X | ||
| else: # config is spmatrix |
There was a problem hiding this comment.
Since this can be set by the user, it would be nicer if there is an error if it's neither sparray nor spmatrix?
| if constructor_name in ("sparse", "sparse_csr"): | ||
| # sparse and sparse_csr are equivalent for legacy reasons | ||
| return sp.sparse.csr_matrix(container, dtype=dtype) | ||
| return _align_api_if_sparse(sp.sparse.csr_array(container, dtype=dtype)) |
There was a problem hiding this comment.
It feels like we should mostly not change this code since this is some utils for testing when you want to test with multiple inputs, in particular both sparray and spmatrix. In other words _convert_container should give you what you specify and not use the config.
Maybe the only thing you could change is that sparse means csr_array rather than csr_matrix? Not even sure TBH. I would not change it in this PR but leave it for later.
| # TODO: Replace when Scipy 1.12 is the minimum supported version | ||
| # fixes for transitioning scipy.sparse function names | ||
| if not SCIPY_VERSION_BELOW_1_12: | ||
| _sparse_eye = scipy.sparse.eye_array |
There was a problem hiding this comment.
It's a bit weird to have different return types depending on the scipy version.
I would rather have these helper functions be called _sparse_eye_array and _sparse_diags_array and always return sparrays?
Maybe I am missing some subtlety here? In case it matters, our minimum scipy version is currently 1.10.0.
There was a problem hiding this comment.
I renamed the helper functions _sparse_eye_array, _sparse_diags_array and _sparse_random_array.
Also, note that there is also already a sklearn function named _sparse_random_matrix defined in sklearn/random_projection.py. That is a long existing function in sklearn and not related to the scipy sparse functions. So I don't think there is any confusion between these names.
|
Thanks @lesteve for the helpful review comments! And yes, it is likely this will require follow-up PRs. Thanks for noting some cases that are likely to need that. The requested changes are in and we've got green checks for CI. |
|
@lesteve I looked up codecov and it‘s fine for me. For instance, I can live with the missing lines in fixes. Those will be removed in the future anyway. The others don‘t seem so important. |
|
Thanks a lot for your continued effort on this @dschult! Let's merge this one and iterate in further PRs. I'll try to clean up my other comments/questions and do another review here or open an issue, whatever seems more convenient. |
|
First follow-up PR (aka merger's remorse 😉) on #31177 (comment): what I was suggesting was to return sparray from if not SCIPY_VERSION_BELOW_1_12:
...
else:
def _sparse_eye_array(m, n=None, *, k=0, dtype=float, format=None):
mat = scipy.sparse.eye(m, n, k=k, dtype=dtype, format=format)
return scipy.sparse.dia_array(mat)Do you see a downside with this? |
|
Another follow-up it seems like this PR breaks one example related to 32 bit indices: See build log for more details. |
I see what you mean now -- and I don't see any problem with making these always return sparray because these are private and we convert any results to spmatrix in the publicly facing functions. I'll put something together.
It looks like one of the datasets is creating sparse arrays with int64 index arrays. Hard for me to tell which dataset right away. I've recreated it locally, so should be able to track it down. traveling today so hopefully solution tonight. |
This PR sets up a config parameter
sparse_interfaceto indicate "sparray" or "spmatrix" outputs, as suggested in #26418.The first commit sets everything up and implements the system for a few modules. Please take a look and provide feedback for whether this is the way to proceed. The next commit(s) will implement these same style of changes throughout the library. If you would prefer they be in separate PRs let me know. (I'll keep Draft status until there is feedback and the full library is convered.)
More specifically, this PR does the following:
sparse_interfaceto the config parameters. (I think this name is better than sparse_format because "format" means csr/coo/lil, etc in the sparse world.) The values it can hold are "sparray" or "spmatrix". Update config tests accordingly.utils._sparse.pywith (private) helper functions. The difference is how much checking is done. Tests added too._as_sparse(x_sparse), raises unless sparse input. converts to interface chosen by config._select_interface_if_sparse(x), allows dense input with no action, sparse input uses_as_sparse._convert_from_spmatrix_to_sparray(x)and_convert_from_sparray_to_spmatrix(x)sklearn/feature_selection/text.pyand adapts tests.sklearn/linear_model/_coordinate_descent.pyno tests change needed.sklearn/manifold/_locally_linear.pyno tests change needed.@thomasjpfan can you see if this does what you had in mind? I tried to pick modules that cover returning sparse, setting estimators to hold sparse, and transforming to sparse, so you can see how this would work.
Let me know if you think
_as_sparseshould be a public function, and if my approach aligns with how you want it. The next steps for this PR are to repeat these type of changes throughout the library.