Fit monotonic curve to data in python
- User
Fit monotonic curve to data in python
Assistant
To fit a monotonic curve to data in Python, you can use several approaches depending on the nature of your data and the type of monotonicity (increasing or decreasing) you want to enforce.
Here’s a step-by-step guide using popular libraries like
scipy,numpy, andsklearn:
✅ Method 1: Using
scipy.interpolate.PchipInterpolatorPCHIP(Piecewise Cubic Hermite Interpolating Polynomial) preserves monotonicity and is good for scattered data.import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import PchipInterpolator # Example data x = np.array([1, 2, 3, 4, 5]) y = np.array([1, 3, 2, 4, 5]) # Not strictly monotonic # Fit monotonic interpolator monotonic_interp = PchipInterpolator(x, y) # Generate smooth curve x_new = np.linspace(min(x), max(x), 200) y_new = monotonic_interp(x_new) # Plot plt.scatter(x, y, color='red', label='Data') plt.plot(x_new, y_new, label='Monotonic Fit (PCHIP)') plt.legend() plt.show()
✅ Method 2: Isotonic Regression (
sklearn.isotonic.IsotonicRegression)This fits a non-decreasing function (can enforce increasing or decreasing).
from sklearn.isotonic import IsotonicRegression # Example data x = np.array([1, 2, 3, 4, 5]) y = np.array([1, 3, 2, 4, 5]) # Fit isotonic regression (increasing=True by default) ir = IsotonicRegression(out_of_bounds='clip') y_pred = ir.fit_transform(x, y) # Plot plt.scatter(x, y, color='red', label='Data') plt.plot(x, y_pred, label='Isotonic Fit', marker='.') plt.legend() plt.show()Note: For a decreasing function, set
increasing=False.
✅ Method 3: Monotonic Spline with
scipy.interpolate.CubicSpline+ constraintsThis is more manual and requires optimization, but allows full control over spline behavior.
However, for most cases, PCHIP or Isotonic Regression should suffice.
📝 Choosing the Right Method
Method Type Pros Cons PchipInterpolatorInterpolation Smooth, preserves monotonicity May overshoot if noisy IsotonicRegressionRegression Non-parametric, fast Piecewise constant, not smooth CubicSpline+ constraintsSmooth spline Very flexible (if coded well) More complex to implement
Would you like help fitting a smooth monotonic curve (like a spline) with explicit constraints?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.