Skip to main content

StepClassDistance

Replace numeric columns with per-row distances to each class centroid.

Usage

Source

StepClassDistance(
    columns,
    target,
    *,
    metric="euclidean",
    log_distance=True,
    eps=0.001,
    prefix="distance",
    keep_original_cols=False,
    role="feature",
    id=None
)

The selected columns are read to learn one centroid per target class, then replaced by one distance_<class> column per class holding each row’s distance to that class’s centroid. Each distance is computed from all the selected columns at once, so no distance column belongs to any one of them. For the distance to a single fixed point, see StepGeoDistance.

See Arguments shared across steps for the arguments this step shares with the others.

Parameters

columns: Selector

Columns to measure distances over. Accepts a single column name, a list of names, a mlfeatures selector such as Selectors.numeric_features() (see Selectors for the full set), or a narwhals or polars selector (narwhals.selectors.numeric(), polars.selectors.numeric()). Selectors are resolved against the data frame’s schema when the recipe is fitted, so the same selector works on any backend. Only numeric columns are meaningful here.

target: str

Name of the column in the training data frame that holds the target classes. Read at fit time only; the column is not declared as an input feature in schema_in().

metric: Metric = "euclidean"

Distance function: "euclidean" (default) or "manhattan".

log_distance: bool = True

Whether to return log(distance + eps) instead of raw distances. Default True.

eps: float = 0.001

Offset inside the log (only used when log_distance is True). Default 0.001.

prefix: str = "distance"

Prefix for the new column names. Default "distance" gives distance_<class>.

keep_original_cols: bool = False

If True, the source columns are kept alongside the distance columns instead of being dropped. Default False.

role: str | None = "feature"

Role assigned to the new distance columns (see Roles). Default "feature".

id: str | None = None
Stable step identifier. Defaults to "class_distance"; a second step of this type in the same recipe becomes "class_distance_2", and passing an id already used in the recipe is an error.

Examples

The two numeric columns are replaced by one distance_<class> column per class label found in target:

df = pd.DataFrame(
    {
        "x": [0.0, 1.0, 10.0, 11.0],
        "y": [0.0, 1.0, 10.0, 11.0],
        "label": ["a", "a", "b", "b"],
    }
)
df
x y label
0 0.0 0.0 a
1 1.0 1.0 a
2 10.0 10.0 b
3 11.0 11.0 b

Specifying the step touches no data, so the recipe reports itself as untrained:

recipe = Recipe().add(
    StepClassDistance(
        s.numeric_features(), target="label", log_distance=False
    )
)
recipe
Recipe (untrained)
  Inputs: no roles assigned
  Steps:
    step_class_distance(select(role='feature', type=NumericType))  [untrained]

fit() learns one centroid per class label and returns a trained recipe:

fitted = recipe.fit(df)
fitted
Recipe (trained)
  Inputs: 3 columns (3 features)
  Steps:
    step_class_distance(x, y → distance_a, distance_b)  [trained]

transform() then replaces the numeric columns with one distance_<class> column per label:

fitted.transform(df)
label distance_a distance_b
0 a 0.707107 14.849242
1 a 0.707107 13.435029
2 b 13.435029 0.707107
3 b 14.849242 0.707107

log_distance (the default) compresses the raw distances:

recipe = Recipe().add(
    StepClassDistance(s.numeric_features(), target="label")
)
fitted = recipe.fit(df)
fitted.transform(df)
label distance_a distance_b
0 a -0.345160 2.698016
1 a -0.345160 2.597940
2 b 2.597940 -0.345160
3 b 2.698016 -0.345160

keep_original_cols keeps the source columns alongside the distances:

recipe = Recipe().add(
    StepClassDistance(
        s.numeric_features(), target="label", keep_original_cols=True
    )
)
fitted = recipe.fit(df)
fitted.transform(df)
x y label distance_a distance_b
0 0.0 0.0 a -0.345160 2.698016
1 1.0 1.0 a -0.345160 2.597940
2 10.0 10.0 b 2.597940 -0.345160
3 11.0 11.0 b 2.698016 -0.345160