Skip to content

ENH Array API for contingency_matrix - #29251

Closed
Tialo wants to merge 42 commits into
scikit-learn:mainfrom
Tialo:array-api/contingency_matrix
Closed

Tialo wants to merge 42 commits into
scikit-learn:mainfrom
Tialo:array-api/contingency_matrix

Conversation

@Tialo

@Tialo Tialo commented Jun 13, 2024 •

Copy link
Copy Markdown
Contributor

Reference Issues/PRs

Towards #26024

What does this implement/fix? Explain your changes.

Added common test like in metrics/tests/test_common.py. As supervised clusters metrics operate with labels imo it is wrong to use dtype_name from yield_namespace_device_dtype_combinations which are float types.

Any other comments?

Should common test check if metric array is on the same device?

@Tialo Tialo changed the title ENH Array API for contingency matrix ENH Array API for contingency_matrix Jun 13, 2024
@github-actions

github-actions Bot commented Jun 13, 2024 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: f1316f5. Link to the linter CI: here

@EmilyXinyi

Copy link
Copy Markdown
Contributor

As supervised clusters metrics operate with labels imo it is wrong to use dtype_name from yield_namespace_device_dtype_combinations which are float types.

Out of curiosity and because I am not familiar with this, do you mind elaborating on why you think that this? Thanks!

@Tialo

Tialo commented Jun 18, 2024

Copy link
Copy Markdown
Contributor Author

As supervised clusters metrics operate with labels imo it is wrong to use dtype_name from yield_namespace_device_dtype_combinations which are float types.

Out of curiosity and because I am not familiar with this, do you mind elaborating on why you think that this? Thanks!

dtype_name is either float32 or float64. It will be more reasonably to use integer types for labels, as usually they are numbers from 0 to n.

But iirc, some metrics, e.g. entropy can use float labels, like 4.0, 2.0, but I am not sure about 4.2, 1.7, etc

@ogrisel

ogrisel commented Jul 8, 2024 •

Copy link
Copy Markdown
Member

I agree with the comment above. To avoid the confusion, the returned value yield_namespace_device_dtype_combinations could be renamed to floating_dtype and the docstring updated accordingly to explain that GPU devices are typically optimized for float32 (or even lower) but some can also offer float64 support.

@ogrisel ogrisel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR. Here is some feedback:

Comment thread sklearn/metrics/cluster/_supervised.py Resolved
Comment thread sklearn/metrics/cluster/_supervised.py Resolved
Comment thread sklearn/metrics/cluster/_supervised.py Resolved
@Tialo
Tialo force-pushed the array-api/contingency_matrix branch from f97c960 to 02d4e6d Compare October 17, 2024 15:41
@Tialo

Tialo commented Dec 2, 2024

Copy link
Copy Markdown
Contributor Author

I am not sure why my test fails with this error.
FAILED metrics/cluster/tests/test_supervised.py::test_contingency_matrix_array_api_sparse - ImportError: array_api_compat is required to dispatch arrays using the API

And if module is not installed, then I don't know why other array-api tests do not fail

Comment thread sklearn/metrics/tests/test_common.py Resolved
Comment thread doc/modules/array_api.rst Resolved
@lucyleeow

Copy link
Copy Markdown
Member

Thanks @Tialo . ping @ogrisel updated with main now.

@lucyleeow

Copy link
Copy Markdown
Member

@Tialo sorry for slow reviews, do you think you can fix the merge conflicts? Thank you!

@Tialo

Tialo commented Dec 1, 2025

Copy link
Copy Markdown
Contributor Author

I am not sure whether I chose the best approach, but I made a function similar to test_array_api_compliance with difference being the dtypes it uses. test_array_api_compliance_supervised uses int dtypes for both true and predicted labels.

https://github.com/Tialo/scikit-learn/blob/f1316f59be1ffdb54117dc16f1c44fc1a875293a/sklearn/metrics/cluster/tests/test_common.py#L290-L313

@lucyleeow lucyleeow left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your patience @Tialo ! Did another quick passover and small nits only.

I am not sure whether I chose the best approach, but I made a function similar to test_array_api_compliance with difference being the dtypes it uses. test_array_api_compliance_supervised uses int dtypes for both true and predicted labels.

Also not sure about this, but @ogrisel may advise.

Comment on lines +258 to +259
labels_true = np.array([0, 0, 1, 1, 2, 2], dtype=int_dtype)
labels_pred = np.array([1, 0, 2, 1, 0, 2], dtype=int_dtype)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that it makes sense for these clustering metrics to take an int but I am not sure if we enforce in (i.e. a float would also work) so I wonder if it is worth testing float as well here?

xref: #32930

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in this file almost all tests depend on integer types, so I chose int for consistency. your point makes sense, this could be done in a separate PR to fix all tests in the file

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in this file almost all tests depend on integer types

are you sure? AFAICT we don't restrict to int dtypes for the other array api checks, we iterate through yield_namespace_device_dtype_combinations

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I meant is that nor current contingency_matrix test check labels other than integer link, neither unsupervised cluster metrics are tested for float labels. dtype_name from yield_namespace_device_dtype_combinations is not used to change label dtypes, only to choose atol to compare with reference labels. link

So if we are to add tests for other dtypes I think it should be added to both non-array api tests as well to unsupervised metrics array api tests

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah I see what you mean, that makes sense.

@lucyleeow lucyleeow Mar 7, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

neither unsupervised cluster metrics are tested for float labels.

I agree, it is odd that dtype is not specified in check_array_api_unsupervised_metric here:

def check_array_api_unsupervised_metric(metric, array_namespace, device, dtype_name):
y_pred = np.array([1, 0, 1, 0, 1, 1, 0])
X = np.random.randint(10, size=(7, 10))

and indeed dtype is only being used to set atol (even though we don't specify dtype, so the atol does not necessarily even match the dtype of the input!).

I would think this was an oversight with check_array_api_unsupervised_metric.

I don't love that we have to change check_array_api_metric and add a new test_array_api_compliance_supervised, in this PR.

I know we don't test float inputs on the non-array API related numpy tests that check the metric has been implementated properly - this makes sense as we seem to convert to int for some metrics anyway. But in terms of array API I wonder if it is worth checking all dtypes. There could be namespace/device-dtype interactions that are worthwhile to test ? If not, I would make supervised and un-supervised checks the same (i.e., int only) instead of adding the extra tests.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @ogrisel to weigh in.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, test_array_api_compliance_supervised in current state is kinda a trap. It's different from test_array_api_compliance in two independent features: (1) input shapes (2) dtype for atol. When new supervised cluster metrics will be adopted, test_array_api_compliance_supervised probably won't suit it, even though inputs would have the right shape, almost every supervised metric returns float output, so (2) would prevent from correct output comparison.

I've seen only 2 cluster metrics that return integer dtypes: contingency_matrix and pair_confusion_matrix. So all other metrics won't actually need int logic from test_array_api_compliance_supervised.

But IMO for those 2 this logic has to be preserved. I see two ways to do it:

  1. Create separate testing function with same logic as in test_array_api_compliance_supervised, but it would have reasonable name test_array_api_int_output or similar.
  2. Change code to
array_api_metric_checkers = {
    "floating": {
        calinski_harabasz_score: [
            check_array_api_unsupervised_metric,
        ],
        davies_bouldin_score: [
            check_array_api_unsupervised_metric,
        ],
    },
    "integer" : {
        contingency_matrix: [
            check_array_api_supervised_metric,
        ],
    },
}

def yield_metric_checker_combinations(metric_checkers=array_api_metric_checkers):
    for output_dtype, dtype_checkers in metric_checkers.items():
        for metric, checkers in dtype_checkers.items():
            for checker in checkers:
                yield output_dtype, metric, checker


@pytest.mark.parametrize(
    "array_namespace, device, dtype_name",
    yield_namespace_device_dtype_combinations(),
    ids=_get_namespace_device_dtype_ids,
)
@pytest.mark.parametrize("output_dtype, metric, check_func", yield_metric_checker_combinations())
def test_array_api_compliance(output_dtype, metric, array_namespace, device, dtype_name, check_func):
    if output_dtype == "integer":
        for int_dtype in ["int32", "int64"]:
            check_func(metric, array_namespace, device, int_dtype)
    else:
        check_func(metric, array_namespace, device, dtype_name)

I prefer the second option.

Comment on lines +164 to +165
classes, class_idx = xp.unique_inverse(xp.asarray(labels_true))
clusters, cluster_idx = xp.unique_inverse(xp.asarray(labels_pred))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add a small comment about this? e.g. "xp.asarray used to convert list inputs to arrays"


.. versionadded:: 0.18

dtype : numeric type, default=np.int64

@lucyleeow lucyleeow Mar 4, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking about this again, since we convert to numpy, this can only accept numpy dtypes. Without guidance array API users may think this could be e.g., xp.int64 / torch.int64.

sp.coo_matrix([[1, 0, 2], [0, 3, 0], [4, 0, 5]], dtype=torch.float32)

gives a somewhat confusing error:

TypeError: Cannot interpret 'torch.float32' as a data type
Full traceback
TypeError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 sp.coo_matrix([[1, 0, 2], [0, 3, 0], [4, 0, 5]], dtype=torch.float32)

File ~/miniconda3/envs/skl-array-api/lib/python3.13/site-packages/scipy/sparse/_coo.py:95, in _coo_base.__init__(self, arg1, shape, dtype, copy, maxprint)
     92         coords = M.nonzero()
     93         self.coords = tuple(idx.astype(index_dtype, copy=False)
     94                              for idx in coords)
---> 95         self.data = getdata(M[coords], copy=copy, dtype=dtype)
     96         self.has_canonical_format = True
     98 if len(self._shape) > 2:

File ~/miniconda3/envs/skl-array-api/lib/python3.13/site-packages/scipy/sparse/_sputils.py:147, in getdata(obj, dtype, copy)
    142 def getdata(obj, dtype=None, copy=False) -> np.ndarray:
    143     """
    144     This is a wrapper of `np.array(obj, dtype=dtype, copy=copy)`
    145     that will generate a warning if the result is an object array.
    146     """
--> 147     data = np.array(obj, dtype=dtype, copy=copy)
    148     # Defer to getdtype for checking that the dtype is OK.
    149     # This is called for the validation only; we don't need the return value.
    150     getdtype(data.dtype)

Maybe we could check (if dispatch is enabled) and raise a more informative error?

Not sure if we've never had to amend the original docstring to add an array API specific note, so not 100% on doing it here.

cc @ogrisel

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add a note in the docstring saying that dtype should be one of numpy dtypes, because for example doing something like this is not quite robust (fails on torch.int4)

try:
    xp_data = xp.asarray(1, dtype=dtype)
except TypeError:
    pass  # it is numpy dtype
else:
    dtype = _convert_to_numpy(xp_data, xp).dtype

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was more thinking of trying someway to check if the dtype is a valid numpy dtype.

But adding a note to the docstring is probably a good idea, it's just that I am not sure if we have ever done this before and wonder if it should be added/highlighted in a special way. I will let @ogrisel weigh in.

@lucyleeow

Copy link
Copy Markdown
Member

Thanks for your patience @Tialo, I few unresolved comments but good for a second review, gentle ping @ogrisel

@OmarManzoor

Copy link
Copy Markdown
Contributor

Closing in favor of #34785

@github-project-automation github-project-automation Bot moved this from In Progress to Done in Array API Aug 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Array API module:metrics Waiting for Second Reviewer First reviewer is done, need a second one!

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

6 participants