PreProcessor
- class mlarena.preprocessor.PreProcessor[source]
Custom transformer for data preprocessing with scikit-learn compatibility.
- preprocessing strategy support
feature analysis and filter feature selection recommendations
encoding recommendations of categorical features based on cardinality and rare category
visualization to compare smoothing parameters for target encoding
- preprocessing execution
scaling of numeric features
target encoding of user specified target encode columns
onehot encoding of the rest of the categorical features
Handles missing values via user specified imputation strategy for numeric and categorical features
Compatible with scikit-learn pipelines and models
- Parameters:
num_impute_strategy (str, default="median") – Strategy for numeric missing values.
cat_impute_strategy (str, default="most_frequent") – Strategy for categorical missing values.
target_encode_cols (List[str], optional) – Columns to apply mean encoding. These are a subgroup of all categorical features.
target_encode_smooth (Union[str, float], default="auto") – Smoothing parameter for target encoding.
drop (str, default="if_binary") – Strategy for dropping categories in OneHotEncoder. Options: ‘if_binary’, ‘first’, None.
sanitize_feature_names (bool, default=True) – Whether to sanitize feature names by replacing special characters.
target_type (str, optional) – Type of target variable. Options: ‘binary’, ‘continuous’, None
- num_impute_strategy
Numeric imputation strategy.
- Type:
str
- cat_impute_strategy
Categorical imputation strategy.
- Type:
str
- num_transformer
Numeric preprocessing pipeline.
- Type:
Pipeline
- onehot_transformer
One-hot encoding preprocessing pipeline.
- Type:
Pipeline
- target_transformer
Target encoding preprocessing pipeline.
- Type:
Pipeline
- transformed_cat_cols
One-hot encoded column names.
- Type:
List[str]
- num_features
The primary list of all identified numerical feature names.
- Type:
List[str]
- cat_features
The primary list of all identified categorical feature names.
- Type:
List[str]
- onehot_encode_cols
A subgroup of cat_features designated for one-hot encoding.
- Type:
List[str]
- target_encode_cols
A subgroup of cat_features designated for target encoding.
- Type:
List[str]
- target_encode_smooth
Smoothing parameter for target encoding.
- Type:
Union[str, float]
- drop
Strategy for dropping categories in OneHotEncoder.
- Type:
str
- sanitize_feature_names
Whether to sanitize feature names by replacing special characters.
- Type:
bool
- target_type
Type of target variable.
- Type:
str
- __init__(num_impute_strategy='median', cat_impute_strategy='most_frequent', target_encode_cols=None, target_encode_smooth='auto', drop='if_binary', sanitize_feature_names=True, target_type=None)[source]
Initialize the transformer.
- Parameters:
num_impute_strategy (str, default="median") – Strategy for numeric missing values.
cat_impute_strategy (str, default="most_frequent") – Strategy for categorical missing values.
target_encode_cols (List[str], optional) – Columns to apply mean encoding. These are a subgroup of all categorical features.
target_encode_smooth (Union[str, float], default="auto") – Smoothing parameter for target encoding.
drop (str, default="if_binary") – Strategy for dropping categories in OneHotEncoder. Options: ‘if_binary’, ‘first’, None.
sanitize_feature_names (bool, default=True) – Whether to sanitize feature names by replacing special characters.
target_type (str, optional) – Type of the target. Options: ‘binary’, ‘continuous’, None.
- fit_transform(X, y=None)[source]
Fit transformer on input data and transform it.
- Parameters:
X (pd.DataFrame) – Input features.
y (pd.Series, optional) – Target variable, required when target_encode_cols is specified.
- Returns:
Transformed data.
- Return type:
pd.DataFrame
- Raises:
ValueError – If target variable y is not provided when target_encode_cols is specified, or if specified columns are not found in input data.
- transform(X)[source]
Transform input data.
- Parameters:
X (pd.DataFrame) – Input features.
- Returns:
Transformed data.
- Return type:
pd.DataFrame
- Raises:
ValueError – If transformer is not fitted.
- static plot_target_encoding_comparison(X_train, y_train, smooth_params, target_encode_col, figsize=(15, 6))[source]
Plot target encoding comparison with different smoothing parameters.
- Parameters:
X_train (pd.DataFrame) – Training features.
y_train (pd.Series) – Target variable.
smooth_params (List[Union[str, float]]) – List of smoothing parameters to compare.
target_encode_col (str) – Column name for target encoding.
figsize (tuple, default=(15, 6)) – Figure size.
- Returns:
Dictionary containing the results for each smoothing parameter.
- Return type:
dict
- static encoding_recommendations(X, high_cardinality_threshold=10, rare_category_threshold=30, prefer_target=True)[source]
Analyze categorical features based on cardinality and rare category to recommend encoding strategy.
- Parameters:
X (pd.DataFrame) – Features.
high_cardinality_threshold (int, default=10) – Number of unique values above which a column is considered high cardinality.
rare_category_threshold (int, default=30) – Minimum samples per category, below which a category is considered rare.
prefer_target (bool, default=True) – Whether to prefer target encoding when both encoding strategies are suitable.
- Returns:
Dictionary containing: - ‘high_cardinality_cols’: List of high cardinality columns - ‘target_encode_cols’: List of columns suitable for target encoding - ‘onehot_encode_cols’: List of columns suitable for one-hot encoding - ‘analysis’: DataFrame showing detailed analysis for each categorical column
- Return type:
dict
- static filter_feature_selection(X, y, task='classification', missing_threshold=0.2, mi_threshold=0.1, n_top_features=None, random_state=42)[source]
Analyzes features and recommends which ones to keep or drop based on data quality metrics.
- Parameters:
X (pd.DataFrame) – Features to analyze.
y (pd.Series) – Target variable.
task (str, default="classification") – Type of ML task - ‘classification’ or ‘regression’.
missing_threshold (float, default=0.2) – Maximum acceptable proportion of missing values.
mi_threshold (float, default=0.1) – Minimum acceptable normalized mutual information score.
n_top_features (int, optional) – If specified, selects this many top features based on mutual information scores. This is applied after filtering out features with too many missing values or no variance. If None, all features meeting the threshold criteria are kept.
random_state (int, default=42) – Random seed for mutual information calculation.
- Returns:
Dictionary containing: - ‘columns_to_drop’: List of all columns recommended for dropping - ‘selected_cols’: List of columns recommended to keep - ‘drop_by_missing’: List of columns with too many missing values - ‘drop_by_unique’: List of columns with only one unique value - ‘drop_by_low_mi’: List of columns with low mutual information - ‘analysis’: DataFrame with detailed analysis for each feature - ‘thresholds’: Dictionary with the thresholds used for filtering
- Return type:
dict
Notes
This method evaluates features based on three main criteria: 1. Missing values: Features with missing values exceeding the threshold are recommended for dropping 2. Unique values: Features with only one unique value (no variance) are recommended for dropping 3. Mutual information: Features with low mutual information with the target are recommended for dropping
If n_top_features is specified, the method will: 1. First apply the basic filtering (missing values, unique values) 2. Then select the top N features based on mutual information scores 3. The mi_threshold will be ignored in this case
Mutual information is calculated with either mutual_info_classif or mutual_info_regression based on user specified task.
- static wrapper_feature_selection(X, y, model, n_max_features=None, min_features_to_select=2, step=1, cv=5, cv_groups=None, cv_variance_penalty=0.1, scoring=None, random_state=42, visualize=True, verbose=True)[source]
Perform wrapper-based feature selection using Recursive Feature Elimination with Cross-Validation.
This method uses RFECV (Recursive Feature Elimination with Cross-Validation) to select the optimal number of features by recursively eliminating features and selecting the best subset based on cross-validation performance with optional variance penalty.
- Parameters:
X (pd.DataFrame) – Input features for feature selection.
y (pd.Series) – Target variable.
model (sklearn estimator) – A supervised learning estimator with a fit method that provides information about feature importance either through a
coef_attribute or through afeature_importances_attribute.n_max_features (int, optional) – Maximum number of features to consider. If None, defaults to n_samples // 10 to prevent overfitting. The method will select the optimal number of features up to this maximum.
min_features_to_select (int, default=2) – Minimum number of features to select.
step (int, default=1) – Number of features to remove at each iteration.
cv (int or CV splitter object, default=5) –
If int: number of folds for default CV strategy (StratifiedKFold or KFold).
If object with .split(): used directly as the CV splitter.
cv_group_by (str, optional) – Column name to group the data for cross-validation. If None, the data is not grouped. Number of folds for cross-validation.
cv_variance_penalty (float, default=0.1) – Penalty weight for cross-validation score variance. Higher values prefer more stable (lower variance) feature sets. The penalized score is calculated as: penalized_score = mean_score - cv_variance_penalty * std_score
scoring (str, optional) – Scoring metric for cross-validation. If None, uses “auc” for classification and “negative rmse” for regressor. Utilize sklearn.metrics.get_scorer_names() to find all supported metrics.
random_state (int, default=42) – Random state for reproducibility.
visualize (bool, default=True) – Whether to display the feature selection plot.
verbose (bool, default=True) – Whether to print detailed results.
cv_groups (str)
- Returns:
Dictionary containing: - ‘selected_features’: List of selected feature names - ‘n_features_selected’: Number of features selected - ‘optimal_score’: Best cross-validation score achieved - ‘optimal_score_std’: Standard deviation of the best score - ‘penalized_score’: Best score with variance penalty applied - ‘cv_scores’: List of mean CV scores for each feature count - ‘cv_scores_std’: List of CV score standard deviations - ‘feature_rankings’: Feature importance rankings from RFE - ‘rfecv_object’: The fitted RFECV object for advanced usage - ‘selection_params’: Dictionary of parameters used for selection
- Return type:
dict
Examples
>>> from sklearn.ensemble import RandomForestClassifier >>> from sklearn.datasets import make_classification >>> import pandas as pd >>> >>> # Create sample data >>> X, y = make_classification(n_samples=100, n_features=20, n_informative=10) >>> X_df = pd.DataFrame(X, columns=[f'feature_{i}' for i in range(20)]) >>> y_series = pd.Series(y) >>> >>> # Perform feature selection >>> results = PreProcessor.wrapper_feature_selection( ... X_df, y_series, ... model=RandomForestClassifier(random_state=42), ... n_max_features=10 ... ) >>> >>> print(f"Selected {results['n_features_selected']} features") >>> print(f"Selected features: {results['selected_features']}")
Notes
The method automatically detects the task type (classification/regression) based on the target variable and sets appropriate cross-validation strategy
For classification tasks with binary targets, uses StratifiedKFold
For regression tasks, uses KFold
The variance penalty helps select feature sets that are not only high-performing but also stable across different data splits
Visualization shows the trade-off between number of features and model performance
- static mlflow_input_prep(data)[source]
Prepare data for MLflow compatibility by converting data types.
- Parameters:
data (pd.DataFrame) – Input data possibly containing category columns.
- Returns:
Data with category columns converted to object dtype and integer columns to float64.
- Return type:
pd.DataFrame
Notes
This function addresses two MLflow compatibility issues: 1. MLflow doesn’t support pandas category dtype, so we convert them to object 2. MLflow doesn’t handle missing values in integer columns, so we convert them to float64