Skip to main content

robustmodels

Robust statistics for Python, from individual measurements to multivariate data.

PyPI version Python versions CI Coverage Downloads License: BSD 3-Clause DOI

User guide · Method references · Source code · Report an issue

A few extreme observations can pull a mean away from the bulk of your data, inflate a standard deviation, or distort a covariance matrix. robustmodels brings established robust estimators into a consistent Python API so you can compare summaries, estimate multivariate structure, and investigate unusual observations.

  • Summarize a sample: robust location, scale, skewness and tail-weight measures.
  • Model multivariate data: six location and covariance estimators, including regularized covariance for data with more variables than observations.
  • Detect outliers: Stahel-Donoho and skewness-adjusted outlyingness with projection depth, as scikit-learn outlier detectors.
  • Fit robust regressions: MM, S and least trimmed squares estimators, resistant to vertical outliers and bad leverage points.
  • Inspect diagnostics: outlier maps, distance-distance plots, tolerance ellipses, adjusted boxplots and outlyingness plots with Matplotlib.
  • Work with familiar tools: NumPy-compatible inputs and the scikit-learn estimator interface for covariance and regression models.
  • Inspect the methods: documented formulas, scientific references, numerical conventions and executable examples.

Installation

python -m pip install robustmodels

Requires Python 3.10+. NumPy, SciPy, scikit-learn and Matplotlib are installed as dependencies. CI tests Python 3.10–3.14 on Linux, Windows and macOS.

Start with one sample

Compare ordinary and robust summaries of a sample containing one extreme value:

import numpy as np
from robustmodels import location, scale

x = [1, 2, 2, 3, 4, 100]

print(f"Mean:           {np.mean(x):.2f}")
print(f"Hodges–Lehmann:  {location.hodges_lehmann(x):.2f}")
print(f"Standard dev.:  {np.std(x, ddof=1):.2f}")
print(f"Qn scale:       {scale.qn(x):.2f}")
Mean:           18.67
Hodges–Lehmann:  3.00
Standard dev.:  39.86
Qn scale:       1.36

The robust summaries remain close to the location and spread of the five values between 1 and 4. Qn is calibrated to estimate the normal standard deviation and includes a finite-sample correction by default.

You can also use location.m_location(x), scale.mad(x) or scale.medcouple(x) to estimate a robust center, scale or skewness. The location guide and scale guide explain their tuning and tradeoffs.

Explore multivariate outliers

Fit a Minimum Covariance Determinant model and compute squared robust Mahalanobis distances. This example adds a shift to ten observations:

import numpy as np
from scipy.stats import chi2
from robustmodels.covariance import MCD

X = np.random.default_rng(0).normal(size=(100, 2))
X[:10] += 10

model = MCD(random_state=0).fit(X)
distances = model.mahalanobis(X)
cutoff = chi2.ppf(0.975, df=X.shape[1])

print("Robust center:", model.location_.round(2).tolist())
print("Rows to inspect:", np.flatnonzero(distances > cutoff).tolist())
Robust center: [0.01, 0.1]
Rows to inspect: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 69]

The ten shifted observations are flagged, along with one unshifted observation in the tail. Treat these as candidates for investigation. The chi-square cutoff is a reference under a multivariate normal model, not an exact finite-sample test or a guaranteed false-positive rate.

The fitted model exposes location_, covariance_, precision_ and support_. Use mahalanobis(new_X) to score new observations; it returns squared distances. Covariance estimators support get_params, set_params and sklearn.base.clone.

For skewed data, where a symmetric scale masks outliers on the short side, use adjusted outlyingness:

from robustmodels.outliers import AdjustedOutlyingness

X = np.random.default_rng(0).lognormal(size=(100, 2))
X[:5] = [-3, -3]  # five outliers on the short side
ao = AdjustedOutlyingness(random_state=0).fit(X)
print("Flagged:", np.flatnonzero(ao.predict(X) == -1).tolist())
Flagged: [0, 1, 2, 3, 4]

See the outlier detection guide.

Fit a robust regression

Robust regression fits the bulk of the data when some responses are wrong. Least trimmed squares also tells you which observations it used:

import numpy as np
from robustmodels.regression import LTSRegressor

rng = np.random.default_rng(0)
X = rng.normal(size=(100, 1))
y = 1 + 2 * X[:, 0] + rng.normal(scale=0.5, size=100)
y[:20] += 15  # twenty outliers

lts = LTSRegressor(random_state=0).fit(X, y)
print(f"Intercept {lts.intercept_:.2f}, slope {lts.coef_[0]:.2f}")
print("Outliers used:", int(lts.support_[:20].sum()))
Intercept 0.95, slope 2.04
Outliers used: 0

The true line is 1 + 2x; least squares gives an intercept of 4.04 and a slope of 1.17. MMRegressor, the default of R's lmrob, combines a 50% breakdown point with 95% efficiency under normal errors, and reports standard errors and p-values with summary(). See the regression guide to choose an estimator and detect outliers.

Plot the diagnostics

Use a fitted estimator to inspect the observations behind its flags:

import matplotlib.pyplot as plt
from robustmodels import plots

ax = plots.outlyingness_plot(ao)
plt.show()

Every plotting function returns a Matplotlib Axes and accepts ax= for subplots. Save with ax.figure.savefig("outlyingness.png", dpi=300). Legends omit empty classes and include observation counts; labels use zero-based row positions. The diagnostic guide includes rendered examples of all five plots, formulas and interpretation. The validation notes explain the pre-release checks and differences from R.

Choose an estimator

Your task A starting point What to consider
Estimate the center of one sample location.hodges_lehmann No tuning parameter; based on pairwise averages.
Estimate spread with resistance to outliers scale.qn or scale.mad Qn uses pairwise differences; MAD uses deviations from a center.
Describe asymmetry scale.medcouple Robust skewness; lmc and rmc describe the tails.
Estimate covariance when observations outnumber variables MCD Supports random or deterministic starts.
Estimate covariance when variables outnumber observations MRCD Regularizes toward an identity target in standardized coordinates.
Explore other multivariate approaches OGK, MVE, SEstimator, MMEstimator Different robustness, efficiency and computational tradeoffs.
Flag outliers in skewed multivariate data AdjustedOutlyingness Adjusted boxplot on many projections; StahelDonohoOutlyingness for symmetric data.
Fit a linear regression with outliers MMRegressor 50% breakdown and 95% efficiency; LTSRegressor and SRegressor are alternatives.

For example, regularized covariance can be fitted to a wide matrix:

import numpy as np
from robustmodels.covariance import MRCD

wide = np.random.default_rng(0).normal(size=(20, 50))
regularized = MRCD().fit(wide)
print(regularized.covariance_.shape)
(50, 50)

See the covariance guide for sample-size requirements, parameters and worked examples.

Available methods

Module Public estimators
robustmodels.location hodges_lehmann, m_location, tau_location, trimmed_mean, winsorized_mean
robustmodels.scale mad, qn, sn, pn, tau_scale, m_scale, medcouple, lmc, rmc
robustmodels.covariance MCD, MRCD, MVE, OGK, SEstimator, MMEstimator
robustmodels.regression MMRegressor, SRegressor, LTSRegressor
robustmodels.outliers StahelDonohoOutlyingness, AdjustedOutlyingness
robustmodels.plots outlier_map, distance_distance, tolerance_ellipse, adjusted_boxplot, outlyingness_plot

The covariance module also exposes h_alpha_n, mcd_consistency and mcd_small_sample. Each public method has a docstring with parameters, return values, examples and references.

Conventions and scope

  • Univariate estimators take finite, one-dimensional samples. Empty samples return NaN; a single observation has zero scale. Handle missing and infinite values before fitting.
  • Covariance and regression models take matrices with observations in rows and variables in columns. Set random_state for methods that use random starts.
  • Qn, Sn and Pn apply finite-sample corrections by default. Use finite_correction=False when you need the asymptotic calibration.
  • Robustness depends on the estimator, sample size, dimension and data. No method in this package is immune to arbitrary contamination. Multivariate subset searches are approximations and do not certify global optima.
  • The package is in early development. Its API may change before version 1.0.

Coming from R? The R equivalents page maps robustbase, rrcov and base R functions to robustmodels. The method references connect the implementations to their scientific sources and explain differences from R conventions. Tests cover statistical properties, edge cases, reference comparisons with R's robustbase and rrcov, and scikit-learn compatibility.

Documentation, contributions and citation

  • Learn: the user guide includes the API reference and examples tested alongside the package.
  • Contribute: see the development guide for setup, checks and release instructions. Bug reports and reproducible examples are welcome in Issues.
  • Follow changes: read the changelog and the roadmap of planned methods.
  • Cite: the DOI 10.5281/zenodo.24169655 refers to all versions; Zenodo also lists a DOI for each release. Citation metadata are in CITATION.cff and GitHub's “Cite this repository” option.

Released under the BSD 3-Clause license.

Metadata

Release files for robustmodels 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for robustmodels 0.1.3
File Size Uploaded Provenance Actions
robustmodels-0.1.3.tar.gz 105.7 kB With provenance Details for robustmodels-0.1.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for robustmodels 0.1.3
File Interpreter ABI Platform Actions
robustmodels-0.1.3-py3-none-any.whl Python 3 none any Details for robustmodels-0.1.3-py3-none-any.whl

Total release size: 155.9 kB

Release files / robustmodels-0.1.3.tar.gz

Download URL robustmodels-0.1.3.tar.gz
Size 105.7 kB
Tags Source
SHA-256 checksum
How to use checksums
2afe9bc91cc0333dd0dc421f7b3deabcd7c4ec10c972977f00828796fa37db77
BLAKE2b-256 checksum
How to use checksums
f1196b766f538975220061d94c8177fe0ee6cf1a78b9722da1ff7f15f4df3103
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 12, 2026.

Transparency log

Release files / robustmodels-0.1.3-py3-none-any.whl

Download URL robustmodels-0.1.3-py3-none-any.whl
Size 50.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
48c08f8450afbb4b2aa66cc81c1c543961e9df3c30b04840f8f27661dc35578d
BLAKE2b-256 checksum
How to use checksums
c24872d895e01f1e940ee1c617cef31444f0f0006561e913b9d566b848dbb8c5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 12, 2026.

Transparency log

Security for robustmodels 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for robustmodels-0.1.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 12, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page