Data
Available preprocessing operations
The name of a preprocessing operation is the name of a transformer class. PreprocessorRegistry resolves the name by first checking the operations registered with it, then searching these modules in order:
| Module | Examples |
|---|---|
sklearn.preprocessing |
StandardScaler, OrdinalEncoder |
sklearn.impute |
SimpleImputer |
The name must match the class name exactly. Any extra keys of an operation are passed to the class constructor.
[workflow.preprocessing]
preprocess = true
operations = [
{ name = "StandardScaler", columns = ["AGE"], with_mean = true },
]
Adding a preprocessing operation
Decorate a transformer class with PreprocessorRegistry.register. The decorator takes the name to register the class under, which defaults to the class name. The operation can then be used by name in the configuration file.
from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixin
from sklearn.utils.validation import validate_data
from medpipe.data import PreprocessorRegistry
@PreprocessorRegistry.register()
class ClipOutliers(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
def __init__(self, lower=0.0, upper=1.0):
self.lower = lower
self.upper = upper
def fit(self, X, y=None):
validate_data(self, X) # Records the names of the columns
return self
def transform(self, X):
return X.clip(self.lower, self.upper)
The operations are chained as pandas data frames, so a transformer has to know the names of its output columns. OneToOneFeatureMixin provides them for a transformer that keeps one output column per input column, as long as fit records the column names with validate_data. Without them, the run stops with "Unable to configure output ... because set_output is not available".
[workflow.preprocessing]
preprocess = true
operations = [
{ name = "ClipOutliers", columns = ["AGE"], lower = 0, upper = 100 },
]
Register the operation before the pipeline is run. Its name is looked up when the preprocessing is built, not when the configuration is validated.
A complete script that registers a model, a preprocessing operation and a metric is shown in the examples.
registry
PreprocessorRegistry
Bases: BaseRegistry[type[Callable]]
Registry for managing and resolving data preprocessing operations.
Source code in medpipe/data/registry.py
utils
Utility functions module.
This module provides utility functions for data manipulation.
Functions: - get_split_idx: Returns the indices for the data splits. - split_data: Split data into train and test or train and recalibration sets. - extract_labels: Extracts prediction labels from data.
get_split_idx
get_split_idx(
idx_list: NDArray,
column: Series | NDArray,
values: list[str] | list[int],
) -> tuple[NDArray, NDArray]
Returns the indices for the data splits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx_list
|
NDArray
|
Indices of the set to split of shape (n_samples,). |
required |
column
|
Series | NDArray
|
Column of shape (n_samples,) used to split the data. |
required |
values
|
list[str] | list[int]
|
Group values that should be in the test or recalibration set. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
train_idx |
NDArray
|
Train indices. |
other_idx |
NDArray
|
Other indices for the test or recalibration set. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If column is not pd.Series or np.ndarray. If values is not a list or a np.ndarray. |
Source code in medpipe/data/utils.py
split_data
split_data(
features: DataFrame,
labels: NDArray,
strategy: Literal["random", "group"],
group_column: str | None = None,
values: list[str] | list[int] | None = None,
test_size: float | None = None,
recalibration_size: float | None = None,
random_state: int | None = None,
) -> tuple[DataFrame, NDArray, DataFrame, NDArray]
Split data into train and test or train and recalibration sets.
If strategy is group then group_column and values must be specified. If strategy is random then test_size or recalibration_size must be specified. If both are specified, the selected value is test_size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
DataFrame
|
Features to split. |
required |
labels
|
NDArray
|
Labels to split. |
required |
strategy
|
('random', 'group')
|
Strategy used to split the data. |
"random"
|
group_column
|
str | None
|
Name of the column used to split with if strategy is group. |
None
|
values
|
list[str] | list[int] | None
|
Values of the group column that do not belong to the train set. |
None
|
test_size
|
float | None
|
Test set size if the strategy is random. |
None
|
recalibration_size
|
float | None
|
Recalibration set size if the strategy is random. |
None
|
random_state
|
int | None
|
Seed controlling the shuffling applied before the random split, for reproducibility. Ignored when strategy is group. |
None
|
Returns:
| Type | Description |
|---|---|
X_train, X_test : pd.DataFrame
|
Train and test / recalibration set. |
y_train, y_test : npt.NDArray
|
Train and test / recalibration labels. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If features is not a pd.DataFrame. If labels is not a np.ndarray. |
ValueError
|
If group_colum and values not specified with group strategy. If test_size or recalibration_size not specified with random strategy. |
Source code in medpipe/data/utils.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
extract_labels
Extracts the prediction labels from the training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame to manipulate. |
required |
labels
|
list[str]
|
List of labels to extract from the data. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
X |
DataFrame
|
DataFrame containing the data. |
y |
NDArray
|
Array containing the prediction labels. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If data is not a pd.DataFrame. |
TypeError
|
If labels is not list[str]. |
ValueError
|
If a prediction label is not a valid key. |
Source code in medpipe/data/utils.py
resolve_subgroup_mask
Generate a boolean mask for a dataset matching a stratum group definition.
Ranges are inclusive so [18, 50] will include 18 and 50 in the range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataset containing the stratum column. |
required |
column
|
str
|
Name of the column to stratify on. |
required |
group
|
Any
|
Group definition. Can be a discrete scalar ('M'), a range tuple (18, 65), a pd.Interval. |
required |
Returns:
| Type | Description |
|---|---|
Series
|
Boolean mask of shape (n_samples,) matching the group criteria. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ValueError
|
If |