LOESS Smoothing Library
LOESS (Locally Estimated Scatterplot Smoothing) is a non-parametric regression method that fits simple models to localized subsets of data to build up a function that describes the deterministic part of the variation. This Python library provides robust implementations for 1D and 2D LOESS smoothing. The current version is 2.1.2, and it typically sees releases for bug fixes and minor improvements, with a stable API.
Common errors
-
ValueError: array must not contain infs or NaNs
cause One or more of the input arrays (`x`, `y`, `z`) contains infinite (`inf`) or Not-a-Number (`NaN`) values.fixFilter out or impute `NaN` and `inf` values from your data before passing them to `loess_1d` or `loess_2d`. Example: `x = x[~np.isnan(x)]` and similarly for other arrays. -
ValueError: x must be sorted for this algorithm to work
cause The input array `x` for `loess_1d` was not provided in ascending sorted order.fixSort your `x` array. If `y` data corresponds to `x`, ensure `y` is reordered accordingly: `sort_idx = np.argsort(x); x_sorted = x[sort_idx]; y_sorted = y[sort_idx]`. -
ValueError: span must be between 0.0 and 1.0
cause The `span` parameter was set to a value outside the valid range (0.0, 1.0].fixAdjust the `span` parameter to be a float value greater than 0.0 and less than or equal to 1.0. For example, `span=0.5` is a common starting point.
Warnings
- gotcha The input array `x` for `loess_1d` must be sorted in ascending order. If `x` is not sorted, the algorithm will not work correctly and will raise a `ValueError`.
- gotcha Input data (`x`, `y` for 1D; `x`, `y`, `z` for 2D) must not contain `inf` or `NaN` values. The library performs checks and will raise a `ValueError` if these are present.
- gotcha The `span` parameter (also known as `alpha` or `bandwidth`) is expected to be a float between 0.0 and 1.0 (exclusive of 0.0, inclusive of 1.0), representing the fraction of data points used for each local regression. Providing a value outside this range will result in a `ValueError`.
Install
-
pip install loess
Imports
- loess_1d
from loess.loess_1d import loess_1d
- loess_2d
from loess.loess_2d import loess_2d
Quickstart
import numpy as np
from loess.loess_1d import loess_1d
# Generate some sample data with noise
x = np.linspace(0, 10, 100)
y = np.sin(x) + np.random.normal(0, 0.5, 100)
# Apply LOESS smoothing
# x must be sorted for loess_1d
y_smoothed, w_out = loess_1d(x, y, xnew=x, span=0.5, degree=1)
print(f"Original x (first 5): {x[:5]}")
print(f"Original y (first 5): {y[:5]}")
print(f"Smoothed y (first 5): {y_smoothed[:5]}")
print(f"Shape of smoothed y: {y_smoothed.shape}")