# Selectors and roles

Recipe steps operate on columns of data, which are chosen with selectors. mlfeatures selectors cover the same ground as Polars selectors, such as all numeric columns (`s.numeric()`), and a step also accepts a Polars selector (`cs.numeric()`) as is. Polars selectors can't target modelling pieces like all "feature" columns, though. mlfeatures enables this by adding roles, modelling-specific tags for columns, and selectors to target them.

> **Note: Key points**
>
> - A step accepts a column name, a list of names, a polars or narwhals selector, or a mlfeatures selector from [Selectors](../../reference/Selectors.md#mlfeatures.Selectors), imported as `s`.
> - mlfeatures selectors choose by name, type, role, or the step that produced a column, and compose with `&`, `|`, `~`, and `-`.
> - `Recipe(..., target="col")` gives a column the `target` role, which keeps it out of feature selectors like `s.numeric_features()`.
> - [Recipe.summary()](../../reference/Recipe.summary.md#mlfeatures.Recipe.summary) lists every column with its dtype, roles, and the step that produced it.
> - Every non-target column is a feature by default; `features=` names them explicitly, and `case_weights` columns are never features.
> - [set_roles()](../../reference/Recipe.set_roles.md#mlfeatures.Recipe.set_roles) attaches custom roles, and `s.has_role()` selects by them.


# Setup

The examples use two datasets from [mlfeatures.data](../../reference/data.md#mlfeatures.data): the credit data, whose target is a string, and a small Ames housing subset, whose target is numeric.


``` python
import polars as pl
import polars.selectors as cs

from mlfeatures import Recipe, StepDummy, StepImputeMedian, StepNormalize
from mlfeatures import Selectors as s
from mlfeatures.data import ames_mini, credit
```


# Selector basics

Pass a polars selector, or a mlfeatures selector from `s`. mlfeatures selectors cover the same name and type checks (`s.numeric()`, `s.starts_with()`, `s.col()`) and compose with set operators, so "every numeric column except `Price`" is one expression.


``` python
recipe = (
    Recipe(data=credit, target="Status")
    .add(StepImputeMedian(cs.numeric()))  # polars selector
    .add(StepNormalize(s.numeric() - s.col("Price")))  # mlfeatures selector
)
fitted = recipe.fit(credit)
fitted
```


    Recipe (trained)
      Inputs: 14 columns (13 features, 1 target)
      Steps:
        step_impute_median(Seniority, Time, Age, Expenses, Income, Assets, Debt, Amount, Price)  [trained]
        step_normalize(Seniority, Time, Age, Expenses, Income, Assets, Debt, Amount)             [trained]


A selector is resolved when the recipe is fitted, against the columns that exist at that point in the pipeline. That is why the fitted recipe lists concrete names, why the same selector works on any backend, and why a later step can pick up columns an earlier step created. The full set is on the [Selectors](../../reference/Selectors.md#mlfeatures.Selectors) reference page.


# Roles: features and targets

Use `Recipe(..., target="col")` to give a column the `target` role, which excludes it from the mlfeatures feature selectors such as `s.numeric_features()`. A polars selector like `cs.numeric()` knows nothing about roles, so it includes the target. That is rarely what you want: a step that works on the target makes it required when the fitted recipe transforms new data, and a column with no target (as at prediction time) then fails the transform.


``` python
recipe = (
    Recipe(data=ames_mini, target="Sale_Price")
    .add(StepNormalize(s.numeric_features()))  # excludes target
    .add(StepNormalize(cs.numeric()))  # includes target
)
fitted = recipe.fit(ames_mini)
fitted
```


    Recipe (trained)
      Inputs: 11 columns (10 features, 1 target)
      Steps:
        step_normalize(Gr_Liv_Area, Year_Built, Garage_Cars, Garage_Area, Latitude, Longitude)              [trained]
        step_normalize(Gr_Liv_Area, Year_Built, Garage_Cars, Garage_Area, Latitude, Longitude, Sale_Price)  [trained]


`s.numeric_features()` is simply `s.numeric()` restricted to the `feature` role. The `_features` variants exist for each type (`s.nominal_features()`, `s.date_features()`, and so on), and `s.features()` and `s.targets()` select by role alone.


# Roles: specifying features

Every column that is not the target is a feature by default, so a feature selector sees all of them. Pass `features=` to name the features yourself: the other columns then carry no role, so selectors ignore them, and [transform()](../../reference/Step.transform.md#mlfeatures.Step.transform) passes them through unchanged.


``` python
recipe = Recipe(
    data=ames_mini,
    target="Sale_Price",
    features=["Gr_Liv_Area", "Year_Built", "Neighborhood"],
).add(StepNormalize(s.numeric_features()))
fitted = recipe.fit(ames_mini)
fitted
```


    Recipe (trained)
      Inputs: 4 columns (3 features, 1 target)
      Steps:
        step_normalize(Gr_Liv_Area, Year_Built)  [trained]


The default is applied when the recipe is fitted, which is why an untrained recipe with only a target reports just that target. One standard role is never a feature: a column declared `case_weights=` holds per-sample weights and is left out of every feature selector.


# Displaying role information

[Recipe.summary()](../../reference/Recipe.summary.md#mlfeatures.Recipe.summary) lists one row per column with its dtype, its roles, and the step that produced it, so after a dummy step the indicator columns show up as features whose source is `dummy`:


``` python
recipe = (
    Recipe(data=ames_mini, target="Sale_Price")
    .add(StepDummy(s.nominal_features()))
    .add(StepNormalize(s.numeric_features()))
)
fitted = recipe.fit(ames_mini)
fitted.summary()
```


shape: (54, 5)

| name                   | dtype   | roles     | source     | sparse |
|------------------------|---------|-----------|------------|--------|
| str                    | str     | str       | str        | bool   |
| "Gr_Liv_Area"          | "float" | "feature" | "original" | false  |
| "Year_Built"           | "float" | "feature" | "original" | false  |
| "Garage_Cars"          | "float" | "feature" | "original" | false  |
| "Garage_Area"          | "float" | "feature" | "original" | false  |
| "Latitude"             | "float" | "feature" | "original" | false  |
| …                      | …       | …         | …          | …      |
| "Exterior_1st_Stucco"  | "float" | "feature" | "dummy"    | false  |
| "Exterior_1st_VinylSd" | "float" | "feature" | "dummy"    | false  |
| "Exterior_1st_Wd Sdng" | "float" | "feature" | "dummy"    | false  |
| "Exterior_1st_WdShing" | "float" | "feature" | "dummy"    | false  |
| "Street_Pave"          | "float" | "feature" | "dummy"    | false  |


# Custom roles

`set_roles(name=[...])` attaches any custom role, a column can carry several roles at once, and `s.has_role()` selects by one. Tagging `Latitude` and `Longitude` as `geo` keeps them out of normalization while they stay features:


``` python
recipe = (
    Recipe(data=ames_mini, target="Sale_Price")
    .set_roles(geo=["Latitude", "Longitude"])
    .add(StepNormalize(s.numeric_features() - s.has_role("geo")))
)
fitted = recipe.fit(ames_mini)
fitted.summary().filter(pl.col("roles").str.contains("geo"))
```


shape: (2, 5)

| name        | dtype   | roles          | source     | sparse |
|-------------|---------|----------------|------------|--------|
| str         | str     | str            | str        | bool   |
| "Latitude"  | "float" | "feature, geo" | "original" | false  |
| "Longitude" | "float" | "feature, geo" | "original" | false  |


# Changing roles part way through

[set_roles()](../../reference/Recipe.set_roles.md#mlfeatures.Recipe.set_roles) labels the columns that arrive with the data, and it does so whatever its position in the recipe. To change a role at a point in the pipeline, use [add_role()](../../reference/Recipe.add_role.md#mlfeatures.Recipe.add_role), [update_role()](../../reference/Recipe.update_role.md#mlfeatures.Recipe.update_role) or [remove_role()](../../reference/Recipe.remove_role.md#mlfeatures.Recipe.remove_role). Each takes effect where it is written: the steps after it see the new role, the steps before it do not, and it can reach columns that earlier steps created. Here the dummy indicators get an `indicator` role, which the normalization that follows leaves out by selecting features without it:


``` python
recipe = (
    Recipe(data=ames_mini, target="Sale_Price")
    .add(StepDummy(s.nominal_features()))
    .add_role(s.has_source("dummy"), role="indicator")
    .add(StepNormalize(s.numeric_features() - s.has_role("indicator")))
)
fitted = recipe.fit(ames_mini)
fitted.summary().filter(pl.col("roles").str.contains("indicator"))
```


shape: (47, 5)

| name                         | dtype | roles                | source  | sparse |
|------------------------------|-------|----------------------|---------|--------|
| str                          | str   | str                  | str     | bool   |
| "Neighborhood_Blueste"       | "int" | "feature, indicator" | "dummy" | false  |
| "Neighborhood_Briardale"     | "int" | "feature, indicator" | "dummy" | false  |
| "Neighborhood_Brookside"     | "int" | "feature, indicator" | "dummy" | false  |
| "Neighborhood_Clear_Creek"   | "int" | "feature, indicator" | "dummy" | false  |
| "Neighborhood_College_Creek" | "int" | "feature, indicator" | "dummy" | false  |
| …                            | …     | …                    | …       | …      |
| "Exterior_1st_Stucco"        | "int" | "feature, indicator" | "dummy" | false  |
| "Exterior_1st_VinylSd"       | "int" | "feature, indicator" | "dummy" | false  |
| "Exterior_1st_Wd Sdng"       | "int" | "feature, indicator" | "dummy" | false  |
| "Exterior_1st_WdShing"       | "int" | "feature, indicator" | "dummy" | false  |
| "Street_Pave"                | "int" | "feature, indicator" | "dummy" | false  |


`update_role(columns, new_role=..., old_role=...)` swaps one role for another, or replaces all of a column's roles when `old_role` is left out, and `remove_role(columns, role=...)` takes a role away. Like a step's `columns`, the first argument can be a name, a list of names, or a selector.
