Repository navigation
Conversation
contingency_matrix
Out of curiosity and because I am not familiar with this, do you mind elaborating on why you think that this? Thanks! |
But iirc, some metrics, e.g. |
|
I agree with the comment above. To avoid the confusion, the returned value |
ogrisel
left a comment
There was a problem hiding this comment.
Thanks for the PR. Here is some feedback:
f97c960 to
02d4e6d
Compare
…y-api/contingency_matrix
…y-api/contingency_matrix
|
I am not sure why my test fails with this error. And if module is not installed, then I don't know why other array-api tests do not fail |
…y-api/contingency_matrix
|
@Tialo sorry for slow reviews, do you think you can fix the merge conflicts? Thank you! |
…y-api/contingency_matrix
|
I am not sure whether I chose the best approach, but I made a function similar to |
lucyleeow
left a comment
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Ah I see what you mean, that makes sense.
There was a problem hiding this comment.
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:
scikit-learn/sklearn/metrics/cluster/tests/test_common.py
Lines 242 to 244 in 81e7a3e
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.
There was a problem hiding this comment.
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:
- Create separate testing function with same logic as in
test_array_api_compliance_supervised, but it would have reasonable nametest_array_api_int_outputor similar. - 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.
| classes, class_idx = xp.unique_inverse(xp.asarray(labels_true)) | ||
| clusters, cluster_idx = xp.unique_inverse(xp.asarray(labels_pred)) |
There was a problem hiding this comment.
Could we add a small comment about this? e.g. "xp.asarray used to convert list inputs to arrays"
…y-api/contingency_matrix
|
|
||
| .. versionadded:: 0.18 | ||
|
|
||
| dtype : numeric type, default=np.int64 |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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).dtypeThere was a problem hiding this comment.
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.
|
Closing in favor of #34785 |
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 usedtype_namefromyield_namespace_device_dtype_combinationswhich are float types.Any other comments?
Should common test check if metric array is on the same device?