multimodel-analysis v0.6.1

Python package · Apache-2.0 · v0.6.1

multimodel-analysis

Compare many scikit-learn models on your data with one call. Five analysers cover classification, regression, clustering, anomaly detection and dimensionality reduction. Each gives you a ranked table, plots, and (where it makes sense) tuning, explanations, saved models and a one-file HTML report.

$ pip install multimodel-analysis
Analysers5 classes, one workflow
Models69 registered, 37 run by default
Python3.10, 3.11, 3.12 (tested)
ExportsCSV, Excel, HTML, JSON, joblib

About the project

multimodel-analysis is an open-source Python package for the first step of most data projects: finding out which kind of model suits your data. You hand it a table. It trains a set of scikit-learn models on the same split, scores them with the same metrics and ranks them, so you can choose a sensible baseline in minutes instead of rewriting the same comparison code.

It builds on scikit-learn, pandas, NumPy, Matplotlib and Seaborn and does not try to replace them. The models it runs are ordinary scikit-learn estimators, optional boosters (XGBoost, LightGBM, CatBoost) and UMAP join when installed, and you can add your own.

The five analysers

ClassUse it toModels (default / total)Ranked by
MultiModelClassifierPredict a category8 / 17Accuracy
MultiModelRegressorPredict a number9 / 19R2 Score
MultiModelClustererFind groups (no target column)7 / 14Silhouette
MultiModelAnomalyDetectorFind unusual rows (no labels needed)6 / 7Agreement (F1 Score if you pass labels)
MultiModelReducerReduce columns, draw 2-D maps7 / 12Trustworthiness

The problem it addresses

Comparing models by hand looks easy, but the same code is rewritten for every project, and small mistakes slip in unnoticed:

  • Each model needs its own fit, predict and metric code, so comparing eight models means many near-identical lines.
  • Models end up compared on different splits or different preprocessing, so the numbers are not comparable.
  • Scaling or imputing the whole dataset before splitting leaks information from the test rows into training.
  • One model that fails to converge raises an error and stops the whole loop.
  • String labels, multi-class averaging and ROC curves for more than two classes each need extra care.
  • Tuning, cross-validation, feature importance, saving the winner and sharing a report are more code again.

How it solves it

ProblemWhat the package does
Repeated boilerplateOne call, run_all_models(), fits and evaluates every default model.
Unfair comparisonOne train/test split and one preprocessing step are shared by all models.
Data leakageScaling (and, with preprocess=True, imputing and encoding) is fitted on training rows only. Cross-validation and tuning refit preprocessing inside every fold.
A failing modelIt is skipped and the reason is stored in failed_models_; the rest still run.
Messy datapreprocess=True fills missing values, scales numbers and one-hot encodes text columns.
Weak default settingstune_models() searches a built-in space per model; cross_validate_models() gives fairer scores.
Black boxesPermutation feature_importance() and partial_dependence() work for every model, including SVM and neural networks.
Reporting and reuseCSV, Excel, HTML and JSON tables, save_html_report(), and save_model() / load_model() that carry the preprocessing along.
Your own modelPass any scikit-learn-style estimator in custom_models and it is ranked next to the built-ins.

Before and after

A plain scikit-learn comparison, shortened to two models and four metrics:

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)
scaler = StandardScaler().fit(X_train)
X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)

rows = []
models = {"Logistic Regression": LogisticRegression(max_iter=1000),
          "Random Forest": RandomForestClassifier()}
for name, model in models.items():
    model.fit(X_train, y_train)
    pred = model.predict(X_test)
    rows.append((name,
                 accuracy_score(y_test, pred),
                 precision_score(y_test, pred, average="weighted"),
                 recall_score(y_test, pred, average="weighted"),
                 f1_score(y_test, pred, average="weighted")))
# ...then sorting, ROC curves, confusion matrices, tuning and exporting.

The same job with the package, for all eight default classifiers:

from multimodel_analysis import MultiModelClassifier

clf = MultiModelClassifier(X, y, test_size=0.2, random_state=42)
models = clf.run_all_models()
clf.show_tabular_report(models)

The measured results section shows the real output of runs like this on public datasets.

Who it is for

A good fit

Students and practitioners who want a quick, fair comparison of model families on tabular data, a first look at structure (groups, outliers, a 2-D map), and a report they can share without writing plotting code.

Not what it is for

Deep learning, time-series or text pipelines, distributed training, or production serving. It compares classical models on tabular data, on a single split unless you ask for cross-validation. See Limitations.

About the author

Uditya Narayan Tiwari

Computer Science Engineering student · AI, machine learning, generative AI, RAG and LLMs

Uditya created and maintains multimodel-analysis and this documentation. The package grew out of the everyday need to compare baseline models quickly and fairly, and it is developed in the open, so issues and suggestions are welcome.

Where to go next

Installation

The package is published on PyPI. It requires Python 3.10 or newer (tested on 3.10, 3.11 and 3.12) and installs numpy (≥1.22), pandas (≥1.4), matplotlib (≥3.5), seaborn (≥0.12) and scikit-learn (≥1.3) as dependencies.

py -m venv .venv
.venv\Scripts\Activate.ps1
py -m pip install multimodel-analysis

Verify the install

python -c "import multimodel_analysis as m; print(m.__version__)"

This should print 0.6.1 or the version you installed.

Optional extras

Install only what you need. Without an extra the matching models are simply left out of include="all"; asking for one by name is reported in failed_models_ with an install hint, never as a crash.

ExtraCommandAdds
excelpip install "multimodel-analysis[excel]"openpyxl, for saving reports as .xlsx
boostpip install "multimodel-analysis[boost]"XGBoost, LightGBM and CatBoost models (classification and regression)
umappip install "multimodel-analysis[umap]"UMAP in MultiModelReducer (umap-learn)
devpip install "multimodel-analysis[dev]"Test and lint tools, for contributors
pip install "multimodel-analysis[excel,boost,umap]"

From source

git clone https://github.com/udityamerit/Multimodel-Analysis-Pacakge.git
cd Multimodel-Analysis-Pacakge
pip install -e ".[dev]"

Quickstart

All five analysers follow the same steps: build the object, run the models, read the table, then plot or save what you need. The code below runs as written with scikit-learn's bundled datasets.

from sklearn.datasets import load_breast_cancer
from multimodel_analysis import MultiModelClassifier

X, y = load_breast_cancer(return_X_y=True, as_frame=True)

clf = MultiModelClassifier(X, y, test_size=0.2, random_state=42)

models = clf.run_all_models()                              # 8 default models, one split
df = clf.show_tabular_report(models, return_df=True)       # ranked by Accuracy

clf.plot_comparison(models, metric="F1 Score")
clf.plot_confusion_matrices(models)
clf.plot_roc_curves(models)
clf.save_report(df, "classification_report.csv")
clf.save_html_report("report.html", title="Breast cancer")  # one-file report
clf.predict(X.head())                                       # best model, original labels

Headless environments

Every plot method takes show_plot=False and save_path="plot.png". Use them on a server, in CI, or whenever you only want the files; otherwise each plot opens through plt.show(). get_summary(save_prefix="out/run1", show_plot=False) writes the CSV table and every plot at once (the folder must already exist).

Runnable notebooks with executed output are in the package repository: see Links & resources.

Choosing a class

Start from the question you are asking:

Do you have a column to predict?What kind of answer do you want?Use
YesA category (yes/no, species, spam)MultiModelClassifier
A number (price, temperature, sales)MultiModelRegressor
NoGroups of similar rowsMultiModelClusterer
Unusual rowsMultiModelAnomalyDetector
Fewer columns, or a 2-D pictureMultiModelReducer

The unsupervised classes accept y as an optional argument. It is never used for fitting, only to add scores (clustering), precision/recall (anomalies) or colours and Class Separation (reduction).

How it works

All five analysers share one workflow and one report style, so what you learn on one carries over to the others.

import multimodel_analysis as mm

tool = mm.MultiModelClassifier(X, y, random_state=0)       # 1. give it your data
models = tool.run_all_models()                              # 2. train the default models
table = tool.show_tabular_report(models, return_df=True)    # 3. ranked results (a DataFrame)
tool.plot_comparison(models)                                # 4. ranked bar chart
best = tool.predict(X_new)                                  # 5. use the best model
  1. Validate and prepare

    By default the data must be numeric and complete, and the package tells you in plain words what is wrong (missing values, text columns, length mismatch, continuous target for classification, invalid test_size). With preprocess=True it cleans the data for you instead; see Messy data. A classification target of any type is label-encoded, and predictions come back in your original labels.

  2. Split

    Classifier and regressor use train_test_split with your test_size (default 0.3) and random_state (default 42). Classification is stratified when stratify=True and every class has at least two samples; otherwise it falls back to an unstratified split without raising. The unsupervised classes fit on all rows and score on them.

  3. Scale (and optionally clean)

    With scaled_data=True (the default) a StandardScaler is fitted on the training rows only and applied to both splits, so no test information leaks into training. With preprocess=True imputing and encoding are fitted on the training rows in the same way.

  4. Train and evaluate, one model at a time

    run_all_models() fits each selected model in turn, then any custom estimators. A model that fails is skipped; the reason goes to failed_models_ and non-fatal notes go to warnings_. n_jobs is forwarded only to estimators that accept it.

  5. Collect, rank and report

    Results are kept in models_ and the fitted estimators in estimators_ (with fit_times_). show_tabular_report() turns the results into a DataFrame sorted best-first (error metrics ascending); plots, predict, explanations and save_model all use the same results.

Constructor options

OptionDefaultApplies toMeaning
X, yrequiredallFeatures (DataFrame or array) and target. y is optional for the unsupervised classes and only used to add scores or colours.
test_size0.3classifier, regressorShare of rows kept for testing.
stratifyTrueclassifierKeep class shares equal in both splits when possible.
scaled_dataTrueallStandardise features (needed by SVM, KNN and linear models). Fitted on training rows only.
preprocessFalseallImpute missing values and encode text columns. Saved with the model.
class_weightNoneclassifier'balanced' for imbalanced classes (reaches Logistic Regression, SVM, Decision Tree, Random Forest, Extra Trees, Ridge Classifier, Linear SVM and LightGBM).
n_clusters3clustererA number, or "auto" to pick it by Silhouette.
contaminationNoneanomaly detectorShare of rows expected to be unusual, from 0 to 0.5. See Anomaly detection.
n_components2reducerNumber of output dimensions.
random_state42allMakes runs repeatable.
n_jobs-1allCPU cores for estimators that support it.
verboseTrueallPrint tables while running. Set False to get only the returned DataFrame.

Messy data: preprocess=True

tool = mm.MultiModelClassifier(df, y, preprocess=True)

The package builds one pipeline, fitted on training rows only:

  • Numeric columns: missing values are filled with the median, then standardised if scaled_data=True.
  • Text and category columns: missing values are filled with the most common value, then one-hot encoded (unseen categories at prediction time are ignored rather than raising).

The same steps are saved with the model, so predict(new_df) accepts raw, un-cleaned rows. With preprocessing on, a one-hot column shows up in feature importance as one row per category (colour_red, colour_green, ...).

Choosing models

Every model is registered under a short key. Default models run with run_all_models(); extra models run when you ask for them. The full list of keys is in the model reference.

tool.run_all_models()                                        # the default set
tool.run_all_models(include=["random_forest", "svm"])         # only these
tool.run_all_models(exclude=["svm"])                          # default set minus these
tool.run_all_models(include="all")                            # default + extra (installed packages only)
tool.run_model("random_forest", n_estimators=300)             # one model, your own settings

tool.default_models()      # keys of the default set
tool.available_models()    # every key, with whether its package is installed
tool.get_model("Random Forest")   # the fitted estimator, by display name

default_models() and available_models(installed_only=False) are also available on the class itself, for example MultiModelClassifier.default_models().

CallRuns
run_all_models()The default set (8 / 9 / 7 / 6 / 7 models for the five classes).
include=[keys]Exactly those models, default or extra. A missing optional package is reported in failed_models_ with an install hint.
exclude=[keys]The default set without these.
include="all"Default and extra models whose package is installed; the others are skipped silently.
custom_models={name: estimator}Your own models, appended after the built-in ones.

Bring your own model

Pass a dictionary of {name: unfitted_estimator}. Anything with scikit-learn's fit and predict works; predict_proba or decision_function additionally gives a classifier ROC AUC. Custom models are fitted on the same split and ranked with the built-ins; a custom model that raises is skipped and listed in failed_models_.

from sklearn.linear_model import SGDClassifier
from multimodel_analysis import MultiModelClassifier

clf = MultiModelClassifier(X, y, test_size=0.2)

models = clf.run_all_models(custom_models={
    "My SGD": SGDClassifier(random_state=0),
})
clf.show_tabular_report(models)   # 8 default models + 1 custom row

XGBoost, LightGBM and CatBoost no longer need to be passed this way: install the boost extra and use include=["xgboost", "lightgbm", "catboost"] or include="all", which also gives them tuning spaces.

Older per-model methods

The original one-model builders (for example Logistic_model(), KNN_model(), Support_vector_model() and evaluate_model()) and the old spelling MultiModelRegressior still work. They are listed under each class in the API reference. New code should prefer run_all_models(include=...) and run_model().

Classification and regression

MultiModelClassifier predicts a category; MultiModelRegressor predicts a number. They share almost everything, including tuning, cross-validation, explanations and saving.

Classification

from sklearn.datasets import load_breast_cancer
from multimodel_analysis import MultiModelClassifier

data = load_breast_cancer(as_frame=True)
clf = MultiModelClassifier(data.data, data.target, test_size=0.3, random_state=0)

models = clf.run_all_models()
table = clf.show_tabular_report(models, return_df=True, sort_by="F1 Score")
clf.plot_comparison(models, metric="F1 Score")
clf.plot_confusion_matrices(models)
clf.plot_roc_curves(models)

Targets can be numbers, strings or categories, binary or multi-class. clf.predict(new_rows) returns your original labels. The report columns are Accuracy, Precision, Recall, F1 Score, ROC AUC and Fit Time (s); see how each metric is computed.

Regression

from sklearn.datasets import load_diabetes
from multimodel_analysis import MultiModelRegressor

data = load_diabetes(as_frame=True)
reg = MultiModelRegressor(data.data, data.target, random_state=0)

models = reg.run_all_models()
reg.show_tabular_report(models, sort_by="RMSE")
reg.plot_comparison(models, metric="R2 Score")
reg.plot_true_vs_predicted(models)

Columns: MAE, MSE, RMSE, R2 Score and Fit Time (s). For error metrics lower is better, and the report sorts accordingly. SVR, Linear SVR and the MLP regressor standardise the target internally, so unscaled targets do not hurt them.

Predict on new data

clf.predict(new_rows)                          # best model of the last report
clf.predict(new_rows, model="Random Forest")   # a specific model, by display name
clf.export_model("Random Forest").predict_proba(new_rows)   # class probabilities

new_rows must have the same columns as the training data. Scaling (and, with preprocess=True, the whole cleaning pipeline) is applied for you. Without model=, the best model of the last report is used, so call show_tabular_report() first. Each run_all_models or tune_models call replaces the fitted models; save the ones you want to keep first (see saving models).

Tuning and cross-validation

Both work for the classifier and the regressor, run on the training split only (the test split stays untouched) and refit preprocessing inside every fold, so there is no leakage.

Cross-validation

One train/test split can be lucky. cross_validate_models scores every model on several folds of the training data:

cv = clf.cross_validate_models(cv=5)                    # default scoring
cv = clf.cross_validate_models(cv=5, scoring="f1_macro",
                               include=["logistic_regression", "random_forest"])
clf.cv_results_      # the same table, kept on the object
clf.cv_failed_       # {model: reason} for models that could not be cross-validated

The table has a <scorer> mean and <scorer> std column per scorer plus Fit Time (s). A small std relative to the gaps between models means the ranking is trustworthy.

Hyper-parameter tuning

Every built-in model has a sensible search space (the tuned parameters are listed in the model reference).

tuned = clf.tune_models(include=["logistic_regression", "random_forest"],
                        search="random", n_iter=20, cv=5)

clf.tuning_results_      # DataFrame: best CV score, best params, candidates tried, search time
clf.best_params_         # {model name: best parameters}
clf.show_tabular_report(tuned)
ArgumentMeaning
search="random"Default. Tries n_iter random combinations (capped at the size of the grid).
search="grid"Tries every combination.
search="halving"Successive halving: quickly drops weak candidates. Fast on big data.
cv, n_iterNumber of folds (default 5) and random candidates (default 20).
scoringAny scikit-learn scorer name, for example "f1" or "neg_root_mean_squared_error". For clustering, a score column such as "Calinski-Harabasz".
param_gridsReplace a model's built-in space: {"knn": {"n_neighbors": [3, 5, 7]}}.
include, excludeWhich models to tune, by key.

tune_models picks the best parameters by cross-validation on the training split, refits them on the whole training split and evaluates on the test split, returning the same result list as run_all_models. Plots, predict and save_model therefore work on tuned models too. A model whose tuning fails is listed in failed_models_; the others carry on. tune_models also exists on MultiModelClusterer; see Clustering.

Clustering

MultiModelClusterer finds groups in data that has no target column. It runs 7 default methods (14 in total), scores each one and shows the groups on a 2-D map.

from sklearn.datasets import make_blobs
import pandas as pd
from multimodel_analysis import MultiModelClusterer

X, y = make_blobs(n_samples=450, centers=3, random_state=11)
X = pd.DataFrame(X, columns=["feature 1", "feature 2"])

cl = MultiModelClusterer(X, n_clusters=3, random_state=0)
models = cl.run_all_models()
cl.show_tabular_report(models)
cl.plot_comparison(models)     # ranked bars
cl.plot_clusters(models)       # scatter plots of the best methods

How many clusters?

  • Pass a number: n_clusters=3.
  • Or let the tool search: n_clusters="auto" picks k by Silhouette.
  • Or look first with cl.find_optimal_k() (a table of k against Inertia and Silhouette) and cl.plot_k_search() (elbow and silhouette curves with the best k marked).

Methods that decide the number themselves (DBSCAN, HDBSCAN, OPTICS, Mean Shift, Affinity Propagation) ignore n_clusters. Their settings are chosen from the data and shown in cl.auto_params_, for example {'DBSCAN': {'eps': ...}}. Rows they leave unassigned are noise and get label -1.

Reading the scores

ColumnMeaningBetter
SilhouetteHow well each row fits its own cluster compared with the next one (−1 to 1). Above 0.5 is clear, 0.25 to 0.5 reasonable, below 0.25 weak.higher
Calinski-HarabaszBetween-cluster spread against within-cluster spread.higher
Davies-BouldinHow similar clusters are to each other.lower
Clusters, Noise PointsWhat the method found. Noise rows are left out of the scores.n/a
Fit Time (s)Seconds to fit.lower
ARI, NMI, V-measure, Homogeneity, CompletenessAgreement with known labels; only filled when you pass y=.higher

A method that finds fewer than two clusters (DBSCAN on some data) gets N/A scores and a warning rather than a crash. DBSCAN can also look better than it is by setting hard rows aside as noise, so compare it with the methods that label every row. With true labels (for example to test the tool on iris), pass them as y= and sort by ARI:

cl = MultiModelClusterer(iris.data, y=iris.target, n_clusters=3)
cl.show_tabular_report(cl.run_all_models(include="all"), sort_by="ARI")

Using the result

cl.assign_clusters("KMeans")      # your data + a `cluster` column
cl.get_labels("KMeans")           # just the labels (numpy array)
cl.cluster_profile("KMeans")      # size and average of every feature per cluster, in your own units
cl.plot_silhouette("KMeans")      # per-row silhouette, grouped by cluster

cluster_profile is the quickest way to name your groups ("young, low spend" / "older, high spend").

Label new rows

cl.predict(new_rows, model="KMeans")

This works for KMeans, MiniBatch KMeans, Gaussian Mixture, Birch, Bisecting KMeans, Mean Shift and Affinity Propagation. The others (the three Agglomerative variants, Spectral, DBSCAN, HDBSCAN, OPTICS) cannot place unseen points and raise a clear TypeError instead of guessing. With no model=, the best-ranked model that can predict is used.

Tuning

cl.tune_models(include=["kmeans", "gaussian_mixture", "dbscan"])
cl.tuning_results_          # best settings and scores
cl.best_params_
cl.tune_models(include=["dbscan"], scoring="Calinski-Harabasz",
               param_grids={"dbscan": {"eps": [0.2, 0.3, 0.5], "min_samples": [4, 8]}})

Big data and messy data

Methods that need memory proportional to n² (Spectral, Agglomerative, Mean Shift, Affinity Propagation, OPTICS) are skipped above a size limit and listed in failed_models_. Pass allow_large=True to run them anyway. KMeans, MiniBatch KMeans, Birch, Gaussian Mixture and DBSCAN always run. For missing values or text columns use MultiModelClusterer(customers, n_clusters=2, preprocess=True).

Anomaly detection

MultiModelAnomalyDetector finds rows that look unlike the rest: faulty sensors, fraud, typos, unusual customers. It needs no labels. It runs 6 default detectors (7 in total) and tells you where they agree. The convention is 1 = anomaly, 0 = normal.

import numpy as np, pandas as pd
from multimodel_analysis import MultiModelAnomalyDetector

rng = np.random.RandomState(0)
normal = rng.randn(300, 3)
faulty = rng.randn(15, 3) * 0.5 + [4, -4, 4]
sensors = pd.DataFrame(np.vstack([normal, faulty]),
                       columns=["temperature", "pressure", "vibration"])

det = MultiModelAnomalyDetector(sensors, contamination=0.05, random_state=0)
models = det.run_all_models()
det.show_tabular_report(models)
det.plot_anomalies(models)

contamination: how many rows to flag

Anomaly detection always needs a cut-off. contamination is the share of rows you expect to be unusual (between 0 and 0.5, so 0.02 means 2%, not 2). Every detector then flags exactly the top share of rows by anomaly score, which is why the Anomalies counts in the table are nearly equal and the models stay comparable. The default is the share of 1s in y if you pass labels, otherwise 5%. Think about your data: fraud might be 0.5%, a sensor fault 2%.

Reading the report

ColumnMeaning
Anomalies, Anomaly Rate (%)How many rows the model flagged.
AgreementHow closely this model's ranking of rows matches the other models (1 = identical). A consensus hint, not accuracy.
Precision, Recall, F1 Score, ROC AUC, Avg PrecisionOnly when you pass y= (1 = known anomaly).
Fit Time (s)Seconds to fit.

Without labels the table is ranked by Agreement; with labels, by F1 Score.

Look at the actual rows

det.top_anomalies(10)               # the 10 strangest rows with their scores
det.assign_anomalies()              # all rows + `anomaly` (0/1) and `anomaly_score` columns
det.get_labels("Isolation Forest")  # 0/1 array
det.get_scores("Isolation Forest")  # higher = stranger
det.plot_scores()                   # score histogram with the cut-off line

Consensus: trust rows many models agree on

votes = det.consensus()             # adds `votes` and `consensus`
votes[votes["consensus"]]           # flagged by more than half of the models
det.consensus(min_votes=5)          # stricter

Judge new rows

det.predict(new_rows, model="Isolation Forest")      # 1 = anomaly
det.score_new(new_rows, model="Isolation Forest")    # the raw scores

The cut-off learned on the training data is reused, so scores are comparable over time. det.save_model(path) keeps the cut-off with the model.

Mixed data, custom detectors, big data

  • Mixed data: MultiModelAnomalyDetector(orders, contamination=0.02, preprocess=True) encodes text columns and fills missing numbers.
  • Your own detector: custom_models={"My Forest": IsolationForest(n_estimators=300)}.
  • Big data: One-Class SVM (above 20,000 rows) and Elliptic Envelope (above 100,000) are skipped unless allow_large=True; skipped models are listed in failed_models_.

Dimensionality reduction

MultiModelReducer squeezes many columns into a few (usually 2, to draw a map). It runs 7 default methods (12 in total) and scores how faithfully each one keeps the structure of your data.

from sklearn.datasets import load_digits
from multimodel_analysis import MultiModelReducer

digits = load_digits()
red = MultiModelReducer(digits.data[:1000], y=digits.target[:1000],
                        n_components=2, random_state=0)

models = red.run_all_models()
red.show_tabular_report(models)
red.plot_comparison(models)
red.plot_embeddings(models, top=4)    # 2-D maps, coloured by y if you gave it

y is optional here; it only colours the maps and feeds Class Separation.

Reading the scores

ColumnQuestion it answersBetter
TrustworthinessAre points that look close on the map really close in the original data?higher (max 1)
ContinuityAre points that were close originally still close on the map?higher (max 1)
Global StructureDo far-apart rows stay far apart?higher
Variance Kept (%)Share of the data's spread that survives (PCA and other reversible methods; empty otherwise).higher
Class SeparationHow well classes are separated on the map (needs y).higher
Can Transform New Datayes if the method can map unseen rows (t-SNE: no).n/a

The table is ranked by Trustworthiness by default (change it with sort_by=). Local scores favour t-SNE and Isomap; PCA keeps the global shape and is the easiest to explain. Pick by purpose: PCA to interpret or to feed another model, t-SNE / UMAP for a picture.

How many components do I need?

k = red.find_n_components(0.95)     # smallest number of PCA components keeping 95% of the variance
red.plot_variance()                 # scree plot: variance per component + running total

What do the components mean? (PCA)

loads = red.get_loadings("PCA")
loads["Component 1"].abs().sort_values(ascending=False).head(5)   # columns that drive component 1

Use the result

red.get_embedding("PCA")                    # new columns: Component 1, Component 2, ...
red.transform(new_rows, model="PCA")        # map unseen rows

emb = red.get_embedding("PCA")              # reduce first, then cluster
MultiModelClusterer(emb, n_clusters=3).run_all_models()

PCA, Kernel PCA, FastICA, Factor Analysis, Truncated SVD, Isomap, LLE and Random Projection (and UMAP, if installed) can transform new rows. t-SNE, Spectral Embedding and MDS cannot: they only embed the data they were fitted on, so they raise a clear TypeError.

Notes

  • Constant columns are tolerated (FastICA ignores them).
  • t-SNE, Kernel PCA, Isomap, LLE, Spectral Embedding and MDS are skipped on large data unless allow_large=True. Limits: t-SNE and LLE 10,000 rows; Kernel PCA, Isomap and Spectral Embedding 8,000; MDS 1,500.
  • UMAP needs the extra: pip install "multimodel-analysis[umap]".

Explainability: which features matter?

A ranked table tells you which model is best. These two tools tell you why it predicts what it predicts. They work for every model in MultiModelClassifier and MultiModelRegressor, including ones with no built-in importance (SVM, KNN, neural networks), because they only use predictions. They need no extra packages and are computed on the test split.

Feature importance (permutation)

Shuffle one column at a time and see how much the test score drops. A big drop means the model relied on that column.

from sklearn.datasets import load_breast_cancer
from multimodel_analysis import MultiModelClassifier

data = load_breast_cancer(as_frame=True)
clf = MultiModelClassifier(data.data, data.target, random_state=0)
models = clf.run_all_models(include=["logistic_regression", "random_forest", "gradient_boosting"])
clf.show_tabular_report(models)       # picks the best model, which the calls below use by default

clf.feature_importance().head(8)              # table, for the best model
clf.plot_feature_importance(top=10)           # ranked bars
clf.plot_feature_importance(model="Random Forest", top=10)

The table has three columns: Feature, Importance (the mean score drop: accuracy for classifiers, R2 for regressors) and Std (the spread over n_repeats shuffles, default 10). 0.10 means shuffling the feature costs 10 points. A feature whose drop is about zero, or whose Std is larger than its Importance, does not help the model. Raise n_repeats for steadier numbers; scoring="f1" (or any scorer name) changes the yardstick; max_rows (default 2000) keeps big datasets fast.

Partial dependence: how does a feature act?

Sweep one feature over its range, keep everything else as it is, and plot the average prediction.

clf.plot_partial_dependence(model="Random Forest")                       # the top features
clf.plot_partial_dependence(["worst radius", "worst concave points"], model="Random Forest")
clf.partial_dependence("worst radius", model="Random Forest", grid_points=6)   # the numbers
  • Classification: the curve is the probability of one class; choose it with class_label=0.
  • Regression: the curve is the predicted value, for example reg.plot_partial_dependence(["bmi", "s5"]).
  • A rising curve means larger values push the prediction up. A flat curve means the feature barely matters.

Read importance with care

Importance says what the model uses, not what causes the outcome. Two strongly related columns share credit: shuffling one is rescued by the other, so both can look less important than they are. Importance is measured on the test split, so it reflects generalisation, not memorisation.

See the charts for real feature-importance and partial-dependence output.

Reports, plots and saving models

Tables

show_tabular_report(models, return_df=True) prints the ranked table and returns it as a DataFrame (sort_by= picks the column). save_report picks the format from the file extension. It exists both as a module function and as a method on every analyser.

ExtensionResult
.csvCSV without the index column
.xlsxExcel workbook (needs the excel extra, i.e. openpyxl). The old .xls format is rejected with a clear message.
.html, .htmHTML table
.jsonJSON array of records
anything elseCSV
from multimodel_analysis import save_report

df = clf.show_tabular_report(models, return_df=True)

save_report(df, "leaderboard.csv")       # module function
clf.save_report(df, "leaderboard.xlsx")  # method with an explicit DataFrame
clf.save_report("leaderboard.json")      # method: reuses the last report
clf.save_report()                        # defaults to report.csv

Passing None or an empty DataFrame prints a warning and writes nothing.

Plots

Every plot method accepts save_path="plot.png" (saves a PNG) and show_plot=False (do not open a window, handy on servers). plot_comparison(models, metric="...") draws one plain, ranked bar chart (best on top, value on every bar) for any metric in the table.

ClassPlots
Classifierplot_comparison, plot_confusion_matrices, plot_roc_curves, plot_feature_importance, plot_partial_dependence
Regressorplot_comparison, plot_true_vs_predicted, plot_feature_importance, plot_partial_dependence
Clustererplot_comparison, plot_clusters (PCA for more than 2 features), plot_k_search, plot_silhouette
Anomaly detectorplot_comparison, plot_anomalies, plot_scores
Reducerplot_comparison, plot_embeddings, plot_variance

Everything at once

tool.get_summary(models, save_prefix="out/run1", show_plot=False)

This writes the CSV table and the PNG plots, all starting with out/run1_. The folder must already exist, otherwise you get an OSError.

One-file HTML report

tool.save_html_report("report.html", title="Breast cancer classification")

A single self-contained page with the results table, every plot (embedded as images) and any warnings or failed models. Nothing else is needed to open it, so it is safe to e-mail or attach. An example report is in the package repository.

Save a model and use it later

tool.save_model("best.joblib", model="Random Forest")     # model + its preprocessing in one file

from multimodel_analysis import load_model
loaded = load_model("best.joblib")
loaded.predict(new_rows)           # raw rows in, original labels out
loaded.predict_proba(new_rows)     # classifiers: a DataFrame of class probabilities
  • Scaling and (with preprocess=True) imputing and encoding are saved with the model, so you do not re-create them.
  • Each class saves what it can do: classifier and regressor predict, clusterer predict, anomaly detector predict and score_new (with the learned cut-off), reducer transform.
  • tool.export_model("Random Forest") returns the same bundle as a TrainedModel object without writing a file; loaded.save(path) writes it.

Security note

Model files are Python pickles (joblib). Only load files you created or trust, exactly as with any pickle. Share the HTML report instead when you only need to show results.

Reading the results

What run_all_models returns

A list with one result per successful model, which you pass to the report, plot and explanation methods. Classifier and regressor results are tuples whose first item is the display name; the unsupervised classes return small result objects (ClusterResult, AnomalyResult, ReductionResult). The fitted estimators are kept on the object:

clf.estimators_["Random Forest"]     # fitted estimator, by display name (or clf.get_model("Random Forest"))
clf.fit_times_                       # seconds per model
clf.failed_models_                   # {model: reason}

How each metric is computed

MetricDefinition in this package
AccuracyCorrect predictions divided by all predictions.
Precision, Recall, F1 ScoreSupport-weighted average over classes (average='weighted', zero_division=0). For binary data this is not the same as the positive-class-only score.
ROC AUCBinary: area under the ROC curve of the positive class. Multiclass: one-vs-rest, support-weighted, over the classes present in the test split. NaN if the model has neither probabilities nor decision scores.
MAE, MSE, RMSEMean absolute error, mean squared error and its square root, in the units of the target (squared units for MSE).
R2 ScoreCoefficient of determination on the test split. 1.0 is perfect, 0.0 matches predicting the mean, and it can be negative.
Silhouette, Calinski-Harabasz, Davies-BouldinInternal clustering scores, computed without noise rows; see clustering scores.
AgreementRank agreement of a detector's anomaly scores with the other detectors.
Trustworthiness, Continuity, Global StructureHow well a low-dimensional map keeps neighbourhoods and distances; see reduction scores.

Sorting

ClassDefault order
ClassifierAccuracy, descending
RegressorR2 Score, descending
ClustererSilhouette, descending
Anomaly detectorAgreement (or F1 Score when y is given)
ReducerTrustworthiness, descending

Pass sort_by="..." to show_tabular_report for any column; error metrics and Davies-Bouldin sort ascending. With a single small test split, differences in the third decimal are noise; use cross-validation before trusting a small gap.

Useful attributes

AttributeMeaning
X_train_scaled, X_test_scaledFeature splits used by every model (scaled only if scaled_data=True). Classifier and regressor.
y_train, y_testTarget splits. For the classifier these are the encoded integer labels.
classes_, n_classes_, label_encoderClassifier only. Original class labels and the fitted encoder.
models_The latest result list.
estimators_, fit_times_Fitted estimators and fit times by display name.
failed_models_{model: reason} for every model that was skipped or failed (missing package, too big, error).
warnings_Non-fatal notes collected while fitting, such as "DBSCAN found only noise".
tuning_results_, best_params_After tune_models(): Model, Best CV <scoring>, Best Params, Candidates, Search Time (s), and the best parameters per model.
cv_results_, cv_failed_After cross_validate_models().
auto_params_Clusterer only. Settings chosen from the data for DBSCAN, Mean Shift and similar methods.

Measured results

These tables and charts were produced by running multimodel-analysis 0.6.1 on public scikit-learn datasets, for all five analysers. Nothing on this page is simulated. Your numbers will differ with other data, splits and library versions.

Click a column header to re-sort. The highlighted row is the one the package ranks first: Accuracy for classification, R2 Score for regression, Silhouette for clustering, Agreement for anomalies and Trustworthiness for reduction. Clustering and anomaly runs here use no labels; an empty cell means the method could not be scored (for example DBSCAN finding one cluster).

Console output of this run

        

Charts produced by the package

Files written with save_path= or get_summary(save_prefix=...). Select a chart to enlarge it.

Metrics calculator

Enter the four cells of a binary confusion matrix to see how the standard metrics are derived. This is a plain calculator for understanding the definitions; it does not call the package. Note that the package reports weighted precision, recall and F1, which average the per-class values by class size.

Confusion matrix (counts)
Accuracy–(TP + TN) / total
Precision–TP / (TP + FP)
Recall–TP / (TP + FN)
Specificity–TN / (TN + FP)
F1 score–2PR / (P + R)
MCC–Matthews correlation

Model reference

37 models run by default and 69 are registered across the five analysers. Use the key in include=[...], exclude=[...], run_model("key") and tune_models(...). The name is what appears in reports and what get_model(...), predict(model=...) and save_model(model=...) expect.

  • Standard models run with run_all_models().
  • Extra models run when you ask, with include="all" or by key.
  • Needs names an optional package (xgboost, lightgbm, catboost, umap-learn). Without it the model is skipped with an install hint, never a crash. See the extras.

MultiModelClassifier: 8 run by default, 17 in total. Tuned parameters are the ones tune_models() searches by default; override them with param_grids. List them in code with MultiModelClassifier.default_models() and MultiModelClassifier.available_models().

KeyNameSetNeedsTuned parameters
logistic_regressionLogistic RegressionStandard—C
svmSVMStandard—C, gamma, kernel
decision_treeDecision TreeStandard—max_depth, min_samples_split, min_samples_leaf, criterion
knnKNNStandard—n_neighbors, weights, p
naive_bayesNaive BayesStandard—var_smoothing
random_forestRandom ForestStandard—n_estimators, max_depth, min_samples_split, min_samples_leaf, max_features
gradient_boostingGradient BoostingStandard—n_estimators, learning_rate, max_depth, subsample
adaboostAdaBoostStandard—n_estimators, learning_rate
extra_treesExtra TreesExtra—n_estimators, max_depth, min_samples_split, min_samples_leaf
hist_gradient_boostingHist Gradient BoostingExtra—learning_rate, max_iter, max_depth, l2_regularization
mlpNeural Network (MLP)Extra—hidden_layer_sizes, alpha, learning_rate_init
ldaLinear Discriminant AnalysisExtra—solver
ridge_classifierRidge ClassifierExtra—alpha
linear_svmLinear SVMExtra—C
xgboostXGBoostExtraxgboostn_estimators, learning_rate, max_depth, subsample, colsample_bytree
lightgbmLightGBMExtralightgbmn_estimators, learning_rate, num_leaves, subsample, colsample_bytree
catboostCatBoostExtracatboostiterations, learning_rate, depth

The same table is in the package repository as docs/models.md.

API reference

Signatures and defaults below are taken from version 0.6.1 and cover every public class, method and function. Select a row to open its parameters and an example. The same list is in the package repository as docs/api.md.

Limitations

Knowing what the package does not do matters more than knowing what it does.

  • One hold-out split by default. Scores come from a single train/test split, so on small datasets rankings can flip with another random_state. Use cross_validate_models() before trusting a small gap.
  • Defaults unless you tune. run_all_models() compares models as configured. A model that loses may win after tune_models(), which searches a small, sensible space rather than every setting.
  • Classical models on tabular data. The package wraps scikit-learn estimators (plus optional XGBoost, LightGBM, CatBoost). It does not do deep learning, images, text or time-series forecasting.
  • Basic preprocessing. With preprocess=True you get imputation, one-hot encoding and scaling. There is no feature engineering, feature selection or outlier handling.
  • Sequential training. Models are fitted one after another. n_jobs only parallelises inside estimators that support it.
  • Weighted averaging. Precision, recall and F1 are support-weighted, which can hide poor performance on a rare class. Look at the confusion matrices for that.
  • Unsupervised scores are not accuracy. Silhouette, Agreement and Trustworthiness describe structure, not correctness. Judge clusters and anomalies with domain knowledge and, where you have them, labels via y=.
  • Some methods cannot handle new rows. Spectral, DBSCAN, HDBSCAN, OPTICS, Agglomerative, t-SNE, Spectral Embedding and MDS only describe the data they were fitted on.
  • Size limits on slow methods. Memory-heavy clustering, anomaly and embedding methods are skipped above fixed row counts unless allow_large=True.
  • Importance is not causation. Permutation importance and partial dependence describe the fitted model on the test split.
  • Saved models are pickles. Only load .joblib files from sources you trust.
  • Plots have a fixed design. If you need custom figures, draw them from show_tabular_report(..., return_df=True) or the fitted estimators.

Troubleshooting

A model is missing from the table

It was skipped or failed. Read the reason: tool.failed_models_ and tool.warnings_. Common causes: an optional package is not installed (pip install "multimodel-analysis[boost]"), the data is too big for a slow method (use allow_large=True or leave it out), or the data does not suit the method (for example too few rows).

It says my data has missing values or text columns

By default the data must be numeric and complete. Clean it yourself, or pass preprocess=True: numbers are filled with the median, scaled, and text columns are filled with the most common value and one-hot encoded.

ROC AUC shows NaN

The model offered neither predict_proba nor decision_function, the AUC calculation failed (a warning is recorded), or a class is missing from the test split.

ValueError: contamination must be a number between 0 and 0.5

contamination is a share of rows: 0.02 means 2%, not 2.

DBSCAN or HDBSCAN found one big cluster, or only noise

These methods choose the number of clusters from the data's density. Check tool.auto_params_ and tool.warnings_, then try tune_models(include=["dbscan"]) or your own param_grids. Noise rows have label -1.

predict() raises a TypeError for a clustering or reduction method

That method cannot place unseen rows (DBSCAN, Spectral, Agglomerative, t-SNE, ...). Use one that can (KMeans, Gaussian Mixture, PCA, ...). Calling predict without model= picks the best-ranked model that works.

The numbers change every run

Pass random_state=0 (or any number) when you create the object.

The split is not stratified

Stratification is skipped, silently, when any class has fewer than two samples. Check the class counts, or pass stratify=False.

No figure appears, or too many windows open

Plots open in a window, or inline in a notebook. In scripts, on a server or in CI use show_plot=False with save_path="x.png", or set MPLBACKEND=Agg.

Saving .xlsx fails, or .xls is rejected

Excel output needs openpyxl: pip install "multimodel-analysis[excel]". The old .xls format is not supported; use .xlsx.

get_summary raises OSError

The folder in save_prefix must already exist. Create it first, for example os.makedirs("out", exist_ok=True).

Why do my results differ from scikit-learn alone?

The tool standardises features (scaled_data=True) and uses a fixed train/test split. Set scaled_data=False to turn scaling off. A different test_size or random_state gives different numbers.

It is slow on a large dataset

Gradient Boosting, Random Forest, SVM and KNN grow quickly with rows. Sub-sample for a first pass, run fewer models with include=[...], and look at fit_times_ to see which one costs the most.

Old code stopped working after upgrading

The original methods (Logistic_model(), KNN_model(), get_summary(), ...) and the old spelling MultiModelRegressior still work. If you find something that does not, please open an issue.

Which Python versions work?

Python 3.10, 3.11 and 3.12 are tested on every change. Version 0.6.0 raised the minimum from 3.8 to 3.10.

Changelog

Release notes for every version after 0.1.3. The full text is in the package's CHANGELOG.md and on the PyPI release history.

0.6.1 current

Documentation release. New readme (also the PyPI page) and a docs/ folder of guides. docs/models.md and docs/api.md are generated from the code. func_code.md was removed in favour of docs/api.md. No behaviour change.

0.6.0

  • New MultiModelAnomalyDetector: 6 default detectors plus SGD One-Class SVM, shared contamination, consensus, top_anomalies, predict / score_new.
  • New MultiModelReducer: PCA, Kernel PCA, FastICA, Factor Analysis, Isomap, LLE, t-SNE, plus Truncated SVD, Spectral Embedding, MDS, Random Projection and UMAP. Scored with Trustworthiness, Continuity, Global Structure, Variance Kept and Class Separation.
  • Explainability for classifiers and regressors: feature_importance, plot_feature_importance, partial_dependence, plot_partial_dependence.
  • save_html_report(path, title=) on every analyser.
  • Minimum Python is now 3.10.

0.5.0

New MultiModelClusterer with 7 default and 7 optional methods, Silhouette / Calinski-Harabasz / Davies-Bouldin scores, optional external scores with y=, n_clusters="auto", find_optimal_k, tune_models, assign_clusters, cluster_profile, predict and the clustering plots.

0.4.0

  • Extra models, run with include=[...] or include="all": Extra Trees, Hist Gradient Boosting, MLP, LDA, Ridge Classifier, Linear SVM (classification); Elastic Net, Bayesian Ridge, Huber, Linear SVR, Extra Trees, Hist Gradient Boosting, MLP (regression).
  • Optional boosters XGBoost, LightGBM and CatBoost via the [boost] extra.
  • default_models() and available_models(installed_only=False).
  • SVR, Linear SVR and the MLP regressor standardise the target internally.
  • plot_comparison redesigned as one ranked bar chart with metric=.

0.3.0

Hyper-parameter tuning: tune_models(search="random" | "grid" | "halving", n_iter, cv, scoring, param_grids) with leak-free cross-validation, plus best_params_ and tuning_results_. Every model ships a default search space.

0.2.0

  • Restructured into core and supervised with a model registry; include / exclude, run_model, get_model, available_models, estimators_ and fit_times_. The old method names keep working through a compatibility layer.
  • preprocess=True (imputation, one-hot encoding, scaling), predict, export_model, save_model and load_model, cross_validate_models, class_weight="balanced" and a Fit Time (s) column.

0.1.4

Bug-fix release: scaled_data now defaults to True, SVC defaults to the RBF kernel, ROC AUC no longer fails silently, warnings_ and failed_models_ added, KNN added to the regressors (9 models), SVR standardises its target. First release with a pyproject.toml, CI and tests.

0.1.3

Classifier and regressor with 8 built-in models each, custom estimators, multi-format save_report, get_summary and the MultiModelRegressior alias. This was the version this site documented before the update.

Links & resources

Everything about the package lives in these places.

ResourceLink
Package on PyPIpypi.org/project/multimodel-analysis
PyPI release historyall published versions
Source code on GitHubudityamerit/Multimodel-Analysis-Pacakge
Report a bug or ask a questionGitHub issues
ChangelogCHANGELOG.md
Download statisticspepy.tech

Guides in the package repository

GuideCovers
getting-started.mdInstall, first run, picking the right class
supervised.mdClassification, regression, tuning, cross-validation
clustering.mdClustering
anomaly-detection.mdAnomaly detection
dimensionality-reduction.mdDimensionality reduction
explainability.mdFeature importance and partial dependence
reports-and-persistence.mdReports, HTML report, saving and loading models
models.mdEvery model key and tuned parameter
api.mdEvery public method with its signature
faq.mdFAQ and troubleshooting

Example notebooks

Notebooks with executed output, in the repository's examples/ folder:

Licence & author

The multimodel-analysis package is released under the Apache License 2.0. The source of this documentation site is released under the MIT licence.

Created and maintained by Uditya Narayan Tiwari.