ronantakizawa/codereview-bench huggingface dataset:
Repository: scikit-learn/scikit-learn
File: sklearn/metrics/tests/test_common.py (Python)

Code before:
        sample_weight=None,
        **metric_kwargs,
    )

    sample_weight = np.array([0.0, 0.1, 2.0, 1.0], dtype=dtype_name)

    check_array_api_metric(
        metric,
        array_namespace,
        device,
        dtype_name,
        a_np=y_true_np,
        b_np=y_pred_np,
        sample_weight=sample_weight,
        **metric_kwargs,
    )


def check_array_api_multiclass_classification_metric(
    metric, array_namespace, device, dtype_name
):
    y_true_np = np.array([0, 1, 2, 3])
    y_pred_np = np.array([0, 1, 0, 2])

    if metric.__name__ == "average_precision_score":
        # we need y_pred_nd to be of shape (n_samples, n_classes
        y_pred_np = np.array(
            [
                [0.7, 0.2, 0.05, 0.05],
                [0.1, 0.8, 0.05, 0.05],
                [0.1, 0.1, 0.7, 0.1],
                [0.05, 0.05, 0.1, 0.8],
            ],
            dtype=dtype_name,
        )

    additional_params = {
        "average": ("micro", "macro", "weighted"),
        "beta": (0.2, 0.5, 0.8),
        "adjusted": (False, True),
    }
    metric_kwargs_combinations = _get_metric_kwargs_for_array_api_testing(
        metric=metric,
        params=additional_params,
    )
    for metric_kwargs in metric_kwargs_combinations:
        check_array_api_metric(
            metric,
            array_namespace,
            device,
            dtype_name,

Review comment (suggestion):
```suggestion
        # we need y_pred_nd to be of shape (n_samples, n_classes)
```
nit

Code after:
        sample_weight=None,
        **metric_kwargs,
    )

    sample_weight = np.array([0.0, 0.1, 2.0, 1.0], dtype=dtype_name)

    check_array_api_metric(
        metric,
        array_namespace,
        device,
        dtype_name,
        a_np=y_true_np,
        b_np=y_pred_np,
        sample_weight=sample_weight,
        **metric_kwargs,
    )


def check_array_api_multiclass_classification_metric(
    metric, array_namespace, device, dtype_name
):
    y_true_np = np.array([0, 1, 2, 3])
    y_pred_np = np.array([0, 1, 0, 2])

    if metric.__name__ == "average_precision_score":
        # we need y_pred_nd to be of shape (n_samples, n_classes)
        y_pred_np = np.array(
            [
                [0.7, 0.2, 0.05, 0.05],
                [0.1, 0.8, 0.05, 0.05],
                [0.1, 0.1, 0.7, 0.1],
                [0.05, 0.05, 0.1, 0.8],
            ],
            dtype=dtype_name,
        )

    additional_params = {
        "average": ("micro", "macro", "weighted"),
        "beta": (0.2, 0.5, 0.8),
        "adjusted": (False, True),
    }
    metric_kwargs_combinations = _get_metric_kwargs_for_array_api_testing(
        metric=metric,
        params=additional_params,
    )
    for metric_kwargs in metric_kwargs_combinations:
        check_array_api_metric(
            metric,
            array_namespace,
            device,
            dtype_name,
Repository: scikit-learn/scikit-learn
File: sklearn/utils/tests/test_response.py (Python)

Code before:
        ),
        (IsolationForest(), "predict", "binary", (10,)),
        (IsolationForest(), "predict", "multiclass", (10,)),
        (DecisionTreeRegressor(), "predict", "binary", (10,)),
        (DecisionTreeRegressor(), "predict", "multiclass", (10,)),
    ],
)
def test_response_values_output_shape_(
    estimator, response_method, target_type, expected_shape
):
    """
    Check that output shape corresponds to docstring description

    - for binary classification, it is a 1d array of shape `(n_samples,)`;
    - for multiclass classification
        - with response_method="predict", it is a 1d array of shape `(n_samples,)`;
        - otherwise, it is a 2d array of shape `(n_samples, n_classes)`;
    - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`;
    - for outlier detection, it is a 1d array of shape `(n_samples,)`;
    - for regression, it is a 1d array of shape `(n_samples,)`.
    """
    X = np.random.RandomState(0).randn(10, 2)
    if target_type == "binary":
        y = np.array([0, 1] * 5)
    elif target_type == "multiclass":
        y = np.arange(10)
    else:  # multilabel
        y = np.array([[0, 1], [1, 0]] * 5)

    clf = estimator.fit(X, y)

    y_pred, _ = _get_response_values(clf, X, response_method=response_method)

    assert y_pred.shape == expected_shape


Review comment (suggestion):
Can the test values for `y` be something like `[0, 1, 2, 3, 0, 1, 2, 3, 3, 0]` so that the test would check for `(10, 4)` for the `multi-class` + `predict_proba` case?

This makes it more obvious that `n_samples` and `n_classes` can be different values.

Code after:
        ),
        (IsolationForest(), "predict", "binary", (10,)),
        (IsolationForest(), "predict", "multiclass", (10,)),
        (DecisionTreeRegressor(), "predict", "binary", (10,)),
        (DecisionTreeRegressor(), "predict", "multiclass", (10,)),
    ],
)
def test_response_values_output_shape_(
    estimator, response_method, target_type, expected_shape
):
    """
    Check that output shape corresponds to docstring description

    - for binary classification, it is a 1d array of shape `(n_samples,)`;
    - for multiclass classification
        - with response_method="predict", it is a 1d array of shape `(n_samples,)`;
        - otherwise, it is a 2d array of shape `(n_samples, n_classes)`;
    - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`;
    - for outlier detection, it is a 1d array of shape `(n_samples,)`;
    - for regression, it is a 1d array of shape `(n_samples,)`.
    """
    X = np.random.RandomState(0).randn(10, 2)
    if target_type == "binary":
        y = np.array([0, 1] * 5)
    elif target_type == "multiclass":
        y = [0, 1, 2, 3, 0, 1, 2, 3, 3, 0]
    else:  # multilabel
        y = np.array([[0, 1], [1, 0]] * 5)

    clf = estimator.fit(X, y)

    y_pred, _ = _get_response_values(clf, X, response_method=response_method)

    assert y_pred.shape == expected_shape
Repository: scikit-learn/scikit-learn
File: sklearn/linear_model/tests/test_coordinate_descent.py (Python)

Code before:
        clf.fit(X, y[:, 0])
    assert len(clf.alphas_) == 10

    # same with alphas array-like
    clf = Estimator(alphas=np.arange(10))
    if clf._is_multitask():
        clf.fit(X, y)
    else:
        clf.fit(X, y[:, 0])
    assert len(clf.alphas_) == 10

    # both are not set => default = 100
    clf = Estimator()
    if clf._is_multitask():
        clf.fit(X, y)
    else:
        clf.fit(X, y[:, 0])
    assert len(clf.alphas_) == 100


def test_enet_path_check_input_false():
    """Test enet_path works with check_input=False and various precompute settings."""
    X, y = make_regression(n_samples=100, n_features=5, n_informative=2, random_state=0)
    X = np.asfortranarray(X)

    # All of these used to raise ValueError, now they should run smoothly
    # Case 1: Testing "auto"
    alphas, _, _ = enet_path(X, y, n_alphas=3, check_input=False)
    assert len(alphas) == 3

    # Case 2: Testing True
    alphas, _, _ = enet_path(X, y, n_alphas=3, check_input=False, precompute=True)
    assert len(alphas) == 3

    # Case 3: Testing False
    alphas, _, _ = enet_path(X, y, n_alphas=3, check_input=False, precompute=False)
    assert len(alphas) == 3

    # Case 4: Testing Multi-output
    X_multi, y_multi = make_regression(
        n_samples=100, n_features=5, n_targets=3, random_state=0
    )
    X_multi = np.asfortranarray(X_multi)
    y_multi = np.asfortranarray(y_multi)
    alphas, _, _ = enet_path(X_multi, y_multi, n_alphas=3, check_input=False)
    assert len(alphas) == 3


Review comment (suggestion):
```suggestion
```

This is uncommon. But instead you can add "Regression test for #32989" in the test docstring.

Code after:
        clf.fit(X, y[:, 0])
    assert len(clf.alphas_) == 10

    # same with alphas array-like
    clf = Estimator(alphas=np.arange(10))
    if clf._is_multitask():
        clf.fit(X, y)
    else:
        clf.fit(X, y[:, 0])
    assert len(clf.alphas_) == 10

    # both are not set => default = 100
    clf = Estimator()
    if clf._is_multitask():
        clf.fit(X, y)
    else:
        clf.fit(X, y[:, 0])
    assert len(clf.alphas_) == 100


@pytest.mark.parametrize("precompute", ["auto", True, False])
def test_enet_path_check_input_false(precompute):
    """Test enet_path works with check_input=False and various precompute settings."""
    X, y = make_regression(n_samples=100, n_features=5, n_informative=2, random_state=0)
    X = np.asfortranarray(X)
    alphas, _, _ = enet_path(X, y, n_alphas=3, check_input=False, precompute=precompute)
Repository: scikit-learn/scikit-learn
File: sklearn/linear_model/tests/test_coordinate_descent.py (Python)

Code before:
    assert len(clf.alphas_) == 10

    # same with alphas array-like
    clf = Estimator(alphas=np.arange(10))
    if clf._is_multitask():
        clf.fit(X, y)
    else:
        clf.fit(X, y[:, 0])
    assert len(clf.alphas_) == 10

    # both are not set => default = 100
    clf = Estimator()
    if clf._is_multitask():
        clf.fit(X, y)
    else:
        clf.fit(X, y[:, 0])
    assert len(clf.alphas_) == 100


def test_enet_path_check_input_false():
    """Test enet_path works with check_input=False and various precompute settings."""
    X, y = make_regression(n_samples=100, n_features=5, n_informative=2, random_state=0)
    X = np.asfortranarray(X)

    # All of these used to raise ValueError, now they should run smoothly
    # Case 1: Testing "auto"
    alphas, _, _ = enet_path(X, y, n_alphas=3, check_input=False)
    assert len(alphas) == 3

    # Case 2: Testing True
    alphas, _, _ = enet_path(X, y, n_alphas=3, check_input=False, precompute=True)
    assert len(alphas) == 3

    # Case 3: Testing False
    alphas, _, _ = enet_path(X, y, n_alphas=3, check_input=False, precompute=False)
    assert len(alphas) == 3

    # Case 4: Testing Multi-output
    X_multi, y_multi = make_regression(
        n_samples=100, n_features=5, n_targets=3, random_state=0
    )
    X_multi = np.asfortranarray(X_multi)
    y_multi = np.asfortranarray(y_multi)
    alphas, _, _ = enet_path(X_multi, y_multi, n_alphas=3, check_input=False)
    assert len(alphas) == 3


Review comment (bug):
```suggestion
```

We also don't need these comments. Instead you could parametrise the precompute param with `@pytest.mark.parametrize` which also makes the different test cases more visible and debuggable in case of future regressions.

Code after:
    assert len(clf.alphas_) == 10

    # same with alphas array-like
    clf = Estimator(alphas=np.arange(10))
    if clf._is_multitask():
        clf.fit(X, y)
    else:
        clf.fit(X, y[:, 0])
    assert len(clf.alphas_) == 10

    # both are not set => default = 100
    clf = Estimator()
    if clf._is_multitask():
        clf.fit(X, y)
    else:
        clf.fit(X, y[:, 0])
    assert len(clf.alphas_) == 100


@pytest.mark.parametrize("precompute", ["auto", True, False])
def test_enet_path_check_input_false(precompute):
    """Test enet_path works with check_input=False and various precompute settings."""
    X, y = make_regression(n_samples=100, n_features=5, n_informative=2, random_state=0)
    X = np.asfortranarray(X)
    alphas, _, _ = enet_path(X, y, n_alphas=3, check_input=False, precompute=precompute)
Repository: scikit-learn/scikit-learn
File: sklearn/ensemble/tests/test_forest.py (Python)

Code before:
    forest_predictive = Forest(random_state=0).fit(X_predictive_train, y_train)
    forest_non_predictive = Forest(random_state=0).fit(X_non_predictive_train, y_train)

    predictive_test_score = forest_predictive.score(X_predictive_test, y_test)

    assert predictive_test_score >= expected_score
    assert predictive_test_score >= forest_non_predictive.score(
        X_non_predictive_test, y_test
    )


@pytest.mark.parametrize("Forest", FOREST_REGRESSORS.values())
def test_non_supported_criterion_raises_error_with_missing_values(Forest):
    """Raise error for unsupported criterion when there are missing values."""
    X = np.array([[0, 1, 2], [np.nan, 0, 2.0]])
    y = [0.5, 1.0]

    forest = Forest(criterion="absolute_error")

    msg = ".*does not accept missing values"
    with pytest.raises(ValueError, match=msg):
        forest.fit(X, y)


@pytest.mark.parametrize("Forest", FOREST_REGRESSORS.values())
def test_friedman_mse_deprecation(Forest):
    with pytest.warns(FutureWarning, match="friedman_mse"):
        _ = Forest(criterion="friedman_mse")


Review comment (suggestion):
```suggestion

# TODO(1.11): remove test with the deprecation of friedman_mse criterion
@pytest.mark.parametrize("Forest", FOREST_REGRESSORS.values())
```

Code after:
    forest_predictive = Forest(random_state=0).fit(X_predictive_train, y_train)
    forest_non_predictive = Forest(random_state=0).fit(X_non_predictive_train, y_train)

    predictive_test_score = forest_predictive.score(X_predictive_test, y_test)

    assert predictive_test_score >= expected_score
    assert predictive_test_score >= forest_non_predictive.score(
        X_non_predictive_test, y_test
    )


@pytest.mark.parametrize("Forest", FOREST_REGRESSORS.values())
def test_non_supported_criterion_raises_error_with_missing_values(Forest):
    """Raise error for unsupported criterion when there are missing values."""
    X = np.array([[0, 1, 2], [np.nan, 0, 2.0]])
    y = [0.5, 1.0]

    forest = Forest(criterion="absolute_error")

    msg = ".*does not accept missing values"
    with pytest.raises(ValueError, match=msg):
        forest.fit(X, y)


# TODO(1.11): remove test with the deprecation of friedman_mse criterion
@pytest.mark.parametrize("Forest", FOREST_REGRESSORS.values())
def test_friedman_mse_deprecation(Forest):
    with pytest.warns(FutureWarning, match="friedman_mse"):
        _ = Forest(criterion="friedman_mse")
Repository: scikit-learn/scikit-learn
File: sklearn/preprocessing/_target_encoder.py (Python)

Code before:

    def get_metadata_routing(self):
        """Get metadata routing of this object.

        Please check :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        .. versionadded:: 1.9

        Returns
        -------
        routing : MetadataRouter
            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
            routing information.
        """
        from sklearn.model_selection import KFold  # avoid circular import

        router = MetadataRouter(owner=self)

        if hasattr(self.cv, "split"):
            splitter = self.cv
        else:
            # Mock splitter if `self.cv` is not a cv generator (no routing needed)
            splitter = KFold(self.cv)
        router.add(
            splitter=splitter,
            method_mapping=MethodMapping().add(caller="fit_transform", callee="split"),
        )

        return router

    def __sklearn_tags__(self):
        tags = super().__sklearn_tags__()
        tags.target_tags.required = True
        return tags


Review comment (suggestion):
```suggestion
        router.add(
            # This works, since none of {None, int, iterable} request any metadata
            # and the machinery here would assign an empty MetadataRequest
            # to it.
            splitter=self.cv,
```

Code after:

    def get_metadata_routing(self):
        """Get metadata routing of this object.

        Please check :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        .. versionadded:: 1.9

        Returns
        -------
        routing : MetadataRouter
            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
            routing information.
        """

        router = MetadataRouter(owner=self)

        router.add(
            # This works, since none of {None, int, iterable} request any metadata
            # and the machinery here would assign an empty MetadataRequest
            # to it.
            splitter=self.cv,
            method_mapping=MethodMapping().add(caller="fit_transform", callee="split"),
        )

        return router

    def __sklearn_tags__(self):
        tags = super().__sklearn_tags__()
        tags.target_tags.required = True
        return tags
Repository: scikit-learn/scikit-learn
File: sklearn/cluster/tests/test_bisect_k_means.py (Python)

Code before:
    # Non-regression test for:
    # https://github.com/scikit-learn/scikit-learn/issues/27081
    rng = np.random.RandomState(0)
    X_train = rng.rand(3000, 10)
    bkm = BisectingKMeans(n_clusters=10, algorithm=algorithm).fit(X_train)

    # predict on scaled data to trigger pathologic case
    # where the inner mask leads to empty bisections.
    X_test = 50 * rng.rand(100, 10)
    labels = bkm.predict(X_test)  # should not crash with idiv by 0
    assert np.isin(np.unique(labels), np.arange(10)).all()


def test_one_feature():
    # Check that no error is raised when there is only one feature
    # Non-regression test for:
    # https://github.com/scikit-learn/scikit-learn/issues/27236
    X = np.random.normal(size=(128, 1))
    BisectingKMeans(bisecting_strategy="biggest_inertia", random_state=0).fit(X)


def test_bisecting_kmeans_custom_init_validation():
    """Test that BisectingKMeans validates center shape correctly with custom init.

    Regression test for issue where validation checked against global n_clusters
    instead of the local split count (2).
    """
    rng = np.random.RandomState(42)
    X = rng.rand(100, 2)

    def my_init(X, n_clusters, random_state):
        return X[:n_clusters]

    # This used to raise ValueError because it checked for 3 seeds instead of 2
    bisect = BisectingKMeans(n_clusters=3, init=my_init, n_init=1, random_state=rng)
    bisect.fit(X)


Review comment (suggestion):
```suggestion
    Regression test for issue #33146
```

Code after:
    # Non-regression test for:
    # https://github.com/scikit-learn/scikit-learn/issues/27081
    rng = np.random.RandomState(0)
    X_train = rng.rand(3000, 10)
    bkm = BisectingKMeans(n_clusters=10, algorithm=algorithm).fit(X_train)

    # predict on scaled data to trigger pathologic case
    # where the inner mask leads to empty bisections.
    X_test = 50 * rng.rand(100, 10)
    labels = bkm.predict(X_test)  # should not crash with idiv by 0
    assert np.isin(np.unique(labels), np.arange(10)).all()


def test_one_feature():
    # Check that no error is raised when there is only one feature
    # Non-regression test for:
    # https://github.com/scikit-learn/scikit-learn/issues/27236
    X = np.random.normal(size=(128, 1))
    BisectingKMeans(bisecting_strategy="biggest_inertia", random_state=0).fit(X)


def test_bisecting_kmeans_custom_init_validation():
    """Test that BisectingKMeans validates center shape correctly with callable init.

    Regression test for issue #33146
    """
    rng = np.random.RandomState(42)
    X = rng.rand(100, 2)

    def my_init(X, n_clusters, random_state):
        return X[:n_clusters]

    bisect = BisectingKMeans(n_clusters=3, init=my_init, n_init=1, random_state=rng)
    bisect.fit(X)
Repository: scikit-learn/scikit-learn
File: sklearn/cluster/tests/test_bisect_k_means.py (Python)

Code before:

@pytest.mark.parametrize("algorithm", ("lloyd", "elkan"))
def test_no_crash_on_empty_bisections(algorithm):
    # Non-regression test for:
    # https://github.com/scikit-learn/scikit-learn/issues/27081
    rng = np.random.RandomState(0)
    X_train = rng.rand(3000, 10)
    bkm = BisectingKMeans(n_clusters=10, algorithm=algorithm).fit(X_train)

    # predict on scaled data to trigger pathologic case
    # where the inner mask leads to empty bisections.
    X_test = 50 * rng.rand(100, 10)
    labels = bkm.predict(X_test)  # should not crash with idiv by 0
    assert np.isin(np.unique(labels), np.arange(10)).all()


def test_one_feature():
    # Check that no error is raised when there is only one feature
    # Non-regression test for:
    # https://github.com/scikit-learn/scikit-learn/issues/27236
    X = np.random.normal(size=(128, 1))
    BisectingKMeans(bisecting_strategy="biggest_inertia", random_state=0).fit(X)


def test_bisecting_kmeans_custom_init_validation():
    """Test that BisectingKMeans validates center shape correctly with custom init.

    Regression test for issue where validation checked against global n_clusters
    instead of the local split count (2).
    """
    rng = np.random.RandomState(42)
    X = rng.rand(100, 2)

    def my_init(X, n_clusters, random_state):
        return X[:n_clusters]

    # This used to raise ValueError because it checked for 3 seeds instead of 2
    bisect = BisectingKMeans(n_clusters=3, init=my_init, n_init=1, random_state=rng)
    bisect.fit(X)


Review comment (suggestion):
```suggestion
    """Test that BisectingKMeans validates center shape correctly with callable init.
```

Code after:

@pytest.mark.parametrize("algorithm", ("lloyd", "elkan"))
def test_no_crash_on_empty_bisections(algorithm):
    # Non-regression test for:
    # https://github.com/scikit-learn/scikit-learn/issues/27081
    rng = np.random.RandomState(0)
    X_train = rng.rand(3000, 10)
    bkm = BisectingKMeans(n_clusters=10, algorithm=algorithm).fit(X_train)

    # predict on scaled data to trigger pathologic case
    # where the inner mask leads to empty bisections.
    X_test = 50 * rng.rand(100, 10)
    labels = bkm.predict(X_test)  # should not crash with idiv by 0
    assert np.isin(np.unique(labels), np.arange(10)).all()


def test_one_feature():
    # Check that no error is raised when there is only one feature
    # Non-regression test for:
    # https://github.com/scikit-learn/scikit-learn/issues/27236
    X = np.random.normal(size=(128, 1))
    BisectingKMeans(bisecting_strategy="biggest_inertia", random_state=0).fit(X)


def test_bisecting_kmeans_custom_init_validation():
    """Test that BisectingKMeans validates center shape correctly with callable init.

    Regression test for issue #33146
    """
    rng = np.random.RandomState(42)
    X = rng.rand(100, 2)

    def my_init(X, n_clusters, random_state):
        return X[:n_clusters]

    bisect = BisectingKMeans(n_clusters=3, init=my_init, n_init=1, random_state=rng)
    bisect.fit(X)