MLPipeline

class mlarena.pipeline.MLPipeline[source]

Custom ML pipeline for classification and regression.

  • Works with scikit-learn compatible models

  • Plug in custom preprocessor to handle data preprocessing

  • Manages model training and predictions

  • Provide global and local model explanation

  • Offer comprehensive evaluation report including key metrics and plots

  • Iterative hyperparameter tuning with cross-validation and optional variance penalty

  • Parallel coordinates plot for disgnosis of the yperparameter tuning search space

  • Threshold analysis to find the optimize threshold based on business preference over precision and recall

  • Compatible with MLflow tracking

  • Supports MLflow deployment

model

A scikit-learn compatible model instance.

Type:

BaseEstimator or None

preprocessor

Data preprocessing pipeline.

Type:

Any or None

config

Optional config for model settings.

Type:

Any or None

task

Type of ML task (‘classification’ or ‘regression’).

Type:

str

n_features

Number of features after preprocessing.

Type:

int

n_train_samples

Sample size of the train data.

Type:

int

both_class

Whether SHAP values include both classes.

Type:

bool

shap_values

SHAP values for model explanation.

Type:

shap.Explanation

X_explain

Processed features for SHAP explanation.

Type:

pd.DataFrame

__init__(model=None, preprocessor=None, config=None)[source]

Initialize the MLPipeline with an optional model, preprocessor, and configuration.

Parameters:
  • model (BaseEstimator, optional) – A scikit-learn compatible model, such as LightGBM or XGBoost, for training and predictions.

  • preprocessor (Any, optional) – A transformer or pipeline used to preprocess the input data.

  • config (Any, optional) – Additional configuration settings for the model, if needed.

fit(X_train, y_train, eval_set=None, early_stopping_rounds=None)[source]

Train the model using the provided training data, after applying preprocessing.

Parameters:
  • X_train (pd.DataFrame) – A DataFrame containing feature columns for training.

  • y_train (pd.Series) – A Series containing the target variable values.

  • eval_set (tuple, optional) – Validation set (X_val, y_val) for early stopping.

  • early_stopping_rounds (int, optional) – Number of rounds without improvement before early stopping.

predict(context, model_input)[source]

Make predictions using the pre-trained model, applying preprocessing to the input data.

Parameters:
  • context (Any) – Optional context information provided by MLflow during the prediction phase.

  • model_input (pd.DataFrame) – The DataFrame containing input features for predictions.

Returns:

Model predictions (probabilities for classification, values for regression).

Return type:

np.ndarray

explain_model(X, plot_size='auto', plot_type='auto', max_features=20, group_remaining_features=True)[source]

Generate SHAP values and plots for model interpretation.

This method: 1. Transforms the input data using the fitted preprocessor 2. Creates a SHAP explainer appropriate for the model type 3. Calculates SHAP values for feature importance 4. Generates a summary plot of feature importance

Parameters:
  • X (pd.DataFrame) – Input features to explain.

  • plot_size (tuple) – Size of the summary plot (width, height).

  • plot_type (str) – Options: “auto”, “beeswarm”, or “summary” - “auto”: tries modern beeswarm plot, falls back to legacy summary if needed - “beeswarm”: always uses modern shap.plots.beeswarm() - “summary”: always uses legacy shap.summary_plot()

  • max_features (int, default=20) – Maximum number of features to display in the summary plot.

  • group_remaining_features (bool, default=True) – Whether to group remaining features (beyond max_features) together and show them as a single “remaining features” entry. If False, remaining features are simply excluded from the plot. Note: Only applies to beeswarm plots; ignored for legacy summary plots.

Returns:

The method stores the following attributes in the class: - self.X_explain : Transformed data with original numeric values - self.shap_values : SHAP values for each prediction - self.both_class : Whether the model outputs probabilities for both classes

Return type:

None

explain_case(n)[source]

Generate SHAP waterfall plot for one specific case.

  • Shows feature contributions

  • Starts from base value

  • Ends at final prediction

  • Shows original feature values for better interpretability

Parameters:

n (int) – Case index (1-based), e.g., n=1 explains the first case.

Returns:

Displays SHAP waterfall plot.

Return type:

None

Notes

  • Requires explain_model() to be called first

  • Shows positive class for binary classification tasks

explain_dependence(feature_1, feature_2=None)[source]

Generate SHAP dependence scatter plot for one or two features.

  • Shows the relationship between a feature and the model’s prediction

  • Can be used to identify feature importance

  • Can be used to identify feature interactions

Parameters:
  • feature_1 (str) – Name of the feature to plot.

  • feature_2 (str, optional) – Name of the second feature to plot, this is used to show the interaction between the two features If None, automatically attempts to pick out the feature column with the strongest interaction.

Returns:

Displays SHAP dependence scatter plot.

Return type:

None

Notes

  • Requires explain_model() to be called first

  • For one-hot encoded features, the feature name should be the encoded feature name

Raises:
  • ValueError – If feature_1 or feature_2 is not found in the dataset

  • UserWarning – If explain_model() has not been called first

evaluate(X_test, y_test, threshold=0.5, beta=1.0, verbose=True, visualize=True, log_model=False)[source]

Evaluate model performance using appropriate metrics.

Parameters:
  • X_test (pd.DataFrame) – Test features DataFrame.

  • y_test (array-like) – One-dimensional true target values. Values must align with X_test by row order; pandas index labels are not used for alignment.

  • threshold (float, default=0.5) – Classification threshold.

  • beta (float, default=1.0) – Beta value for F-beta score.

  • verbose (bool, default=True) – If True, prints detailed evaluation metrics.

  • visualize (bool, default=True) – If True, displays relevant visualization plots.

  • log_model (bool, default=False) – If True, logs model to MLflow.

Returns:

Dictionary containing evaluation metrics. For classification, includes threshold, precision, recall, F-scores, and AUC. For regression, includes RMSE, R², and other regression metrics.

Return type:

dict

static can_use_spark_tuning()[source]

Check if Spark-based hyperparameter tuning is available.

Returns:

True if Spark tuning is available, False otherwise.

Return type:

bool

static tune(X, y, algorithm, preprocessor, param_ranges, max_evals=500, random_state=42, beta=1, early_stopping=50, n_startup_trials=5, n_warmup_steps=0, verbose=0, cv=5, cv_variance_penalty=0.1, visualize=True, task=None, tune_metric=None, log_best_model=False, disable_optuna_logging=True, configure_plotly=True, show_progress_bar=True, use_spark=False, n_jobs=None, study_name=None, mlflow_storage=None)[source]

Static method to tune hyperparameters using Optuna.

Parameters:
  • X (pd.DataFrame) – Features.

  • y (array-like) – One-dimensional target values. Values must align with X by row order; pandas index labels are not used for alignment.

  • algorithm (class) – ML algorithm class (e.g., lgb.LGBMClassifier).

  • preprocessor (PreProcessor or None) – Data preprocessing pipeline.

  • param_ranges (dict) – Dictionary of parameter ranges for Optuna. e.g., {‘n_estimators’: (50, 500), ‘max_depth’: (3, 10)} Specify as tuple (min, max) for int/float or list for categorical.

  • max_evals (int, default=500) – Maximum number of evaluations.

  • random_state (int, default=42) – Random seed for reproducibility.

  • beta (float, default=1.0) – Beta value for F-beta score optimization. beta > 1 gives more weight to recall. beta < 1 gives more weight to precision.

  • early_stopping (int, default=50) – Number of trials without improvement before stopping the optimization process. If None, will run for max_evals trials.

  • n_startup_trials (int, default=5) – Number of trials to run before pruning starts.

  • n_warmup_steps (int, default=0) – Number of steps per trial to run before pruning.

  • verbose (int, default=0) – Verbosity level. Only used if algorithm supports it.

  • cv (int, default=5) – Number of splits for cross-validation.

  • cv_variance_penalty (float, default=0.1) – Weight for penalizing high variance in cross-validation scores.

  • visualize (bool, default=True) – If True, displays relevant visualization plots.

  • task (str, optional) – Task type (‘classification’ or ‘regression’). If None, will be automatically detected.

  • tune_metric (str, optional) – Metric to optimize during hyperparameter tuning. If None, defaults to ‘auc’ for classification and ‘rmse’ for regression. Classification metrics: ‘auc’, ‘f1’, ‘accuracy’, ‘log_loss’, ‘brier_score’, ‘mcc’ Regression metrics: ‘rmse’, ‘mae’, ‘median_ae’, ‘smape’, ‘nrmse_mean’, ‘nrmse_iqr’, ‘nrmse_std’

  • log_best_model (bool, default=False) – If True, logs the best model to MLflow.

  • disable_optuna_logging (bool, default=True) – If True, suppresses Optuna’s verbose logging.

  • configure_plotly (bool, default=True) – If True, automatically configures Plotly renderer for optimal display across different environments including GitHub.

  • show_progress_bar (bool, default=True) – If True, displays a progress bar during optimization.

  • use_spark (bool, default=False) – If True, uses Spark for distributed hyperparameter tuning. Requires MLflow with Spark support (e.g., on Databricks).

  • n_jobs (int, optional) – Number of parallel Spark jobs for hyperparameter tuning. Only used when use_spark=True. If None, uses Spark default.

  • study_name (str, optional) – Name for the MLflow Spark study. If None, auto-generates one. Only used when use_spark=True.

  • mlflow_storage (str, optional) – MLflow storage URI for the Spark study. If None, uses current MLflow tracking URI. Only used when use_spark=True.

Returns:

Dictionary containing: - best_params: Best hyperparameters found - best_pipeline: Best pipeline model - study: Optuna study object - model_info: MLflow model info (if logged) - Various test and CV metrics based on task type

Return type:

dict

static threshold_analysis(y_true, y_pred_proba, beta=1.0, method='bootstrap', cv_splits=5, bootstrap_iterations=100, random_state=42)[source]

Identify the optimal threshold that maximizes F-beta score using CV or bootstrap.

Parameters:
  • y_true (array-like) – One-dimensional true labels.

  • y_pred_proba (array-like) – One-dimensional predicted probabilities. Values are paired with y_true by row order; pandas index labels are not used for alignment.

  • beta (float, default=1.0) – F-beta score parameter.

  • method (str, default='bootstrap') – Method to use for threshold selection: - ‘cv’: Cross-validation (faster, deterministic splits) - ‘bootstrap’: Bootstrap resampling (more robust, with confidence intervals)

  • cv_splits (int, default=5) – Number of folds for cross-validation when method=’cv’.

  • bootstrap_iterations (int, default=100) – Number of bootstrap samples when method=’bootstrap’.

  • random_state (int, default=42) – Random state for reproducibility.

Returns:

Dictionary containing: - optimal_threshold: Mean of thresholds across iterations/splits - threshold_std: Standard deviation of thresholds - threshold_values: List of individual thresholds For bootstrap method, also includes: - ci_lower: Lower bound of 95% confidence interval - ci_upper: Upper bound of 95% confidence interval

Return type:

dict