Inaccurate error message for parameter passing in Pipeline with enable_metadata_routing=True

### Describe the issue linked to the documentation

**The following error message is inaccurate:** 

```
Passing extra keyword arguments to Pipeline.transform is only supported if enable_metadata_routing=True, which you can set using sklearn.set_config.  
```

**This can easily be done using `**params` as described in the documentation for sklearn.pipeline:** https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline.fit 

**Please consider the following example:**

```py
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from scipy.sparse import csr_matrix
import pandas as pd
import numpy as np

class DummyTransformer(BaseEstimator, TransformerMixin):
    def __init__(self):
        self.feature_index_sec = None  # initialize attribute

    def transform(self, X, feature_index_sec=None, **fit_params):
        if feature_index_sec is None:
            raise ValueError("Missing required argument 'feature_index_sec'.")
            
        print(f"Transform Received feature_index_sec with shape: {feature_index_sec.shape}")
        return X

    def fit(self, X, y=None, feature_index_sec=None, **fit_params):
        print(f"Fit Received feature_index_sec with shape: {feature_index_sec.shape}")
        return self

    def fit_transform(self, X, y=None, feature_index_sec=None, **fit_params):
        self.fit(X, y, feature_index_sec, **fit_params)  # feature_index_sec is passed with other parameters
        return self.transform(X, feature_index_sec, **fit_params)

feature_matrix = csr_matrix(np.random.rand(10, 5))
train_idx = pd.DataFrame({'FileDate_ClosingPrice': np.random.rand(10)})

transformer = DummyTransformer()
pipe = Pipeline(steps=[('DummyTransformer', transformer)])

pipe.fit_transform(feature_matrix, DummyTransformer__feature_index_sec=train_idx)

# this line creates the error
pipe.transform(feature_matrix, DummyTransformer__feature_index_sec=train_idx)

```
**Which outputs:**

```
Fit Received feature_index_sec with shape: (10, 1)
Transform Received feature_index_sec with shape: (10, 1)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
File /tmp/test.py:35
     32 pipe.fit_transform(feature_matrix, DummyTransformer__feature_index_sec=train_idx)
     34 # this line creates the error
---> 35 pipe.transform(feature_matrix, DummyTransformer__feature_index_sec=train_idx)

File ~/micromamba/lib/python3.12/site-packages/sklearn/pipeline.py:896, in Pipeline.transform(self, X, **params)
    863 @available_if(_can_transform)
    864 def transform(self, X, **params):
    865     """Transform the data, and apply `transform` with the final estimator.
    866 
    867     Call `transform` of each transformer in the pipeline. The transformed
   (...)
    894         Transformed data.
    895     """
--> 896     _raise_for_params(params, self, "transform")
    898     # not branching here since params is only available if
    899     # enable_metadata_routing=True
    900     routed_params = process_routing(self, "transform", **params)

File ~/micromamba/lib/python3.12/site-packages/sklearn/utils/_metadata_requests.py:158, in _raise_for_params(params, owner, method)
    154 caller = (
    155     f"{owner.__class__.__name__}.{method}" if method else owner.__class__.__name__
    156 )
    157 if not _routing_enabled() and params:
--> 158     raise ValueError(
    159         f"Passing extra keyword arguments to {caller} is only supported if"
    160         " enable_metadata_routing=True, which you can set using"
    161         " `sklearn.set_config`. See the User Guide"
    162         " <https://scikit-learn.org/stable/metadata_routing.html> for more"
    163         f" details. Extra parameters passed are: {set(params)}"
    164     )

ValueError: Passing extra keyword arguments to Pipeline.transform is only supported if enable_metadata_routing=True, which you can set using `sklearn.set_config`. See the User Guide <https://scikit-learn.org/stable/metadata_routing.html> for more details. Extra parameters passed are: {'DummyTransformer__feature_index_sec'}
```

**Request**

- The error message should be updated to clarify that parameters can already be passed using the **params (e.g., StepName__param_name) syntax, which is unrelated to metadata routing.
- Additionally, I was unable to find any example of using enable_metadata_routing=True to pass parameters, either in the documentation or in the wild. It would be helpful if the documentation provided a working example of passing parameters using metadata routing, especially for custom transformers.

### Suggest a potential alternative/fix

_No response_

COMMENT:
The challenge is that I cannot even find a working example of using
metadata routing to pass feature_index_sec via .transform().
Adding set_config(enable_metadata_routing=True) does not help, and produces
the error "TypeError: Pipeline.transform got unexpected argument(s)
{'DummyTransformer__feature_index_sec'}, which are not routed to any
object." ChatGPT cannot solve this question.  I have tried many variations
and also posted it on stackoverflow here:

https://stackoverflow.com/questions/79372602/pass-parameters-to-custom-transformer-in-sklearn/79373117#79373117

The accepted answer does not work for .transform().

On Wed, Jan 22, 2025 at 3:52 AM Loïc Estève ***@***.***>
wrote:

> We looked a bit at it with @StefanieSenger
> <https://github.com/StefanieSenger> and my current understanding is the
> following:
>
>    - the error message is kind of right (improvement suggestions would be
>    more than welcome of course).
>    - if you want to pass arguments to Pipeline.transform maybe you want
>    to give a go to metadata routing (not a metada-routing expert so I could
>    well be wrong)
>
> cc @adrinjalali <https://github.com/adrinjalali> who may have a more
> informed opinion.
>
> —
> Reply to this email directly, view it on GitHub
> <https://github.com/scikit-learn/scikit-learn/issues/30692#issuecomment-2606770856>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AAQCS46NAMF3WZ5IGQRN5JT2L5S7LAVCNFSM6AAAAABVTHJOU2VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDMMBWG43TAOBVGY>
> .
> You are receiving this because you authored the thread.Message ID:
> ***@***.***>
>

Labels: Documentation