Okay, let's look at fitting monotonic curves to data in Python. There are several ways to approach this, depending on the smoothness you need and the underlying assumptions. The two most common and effective methods are:
- Isotonic Regression (using PAVA): This method finds the best least-squares fit among all possible monotonic functions. The result might be piecewise constant (a step function) if the data strongly violates monotonicity. It guarantees monotonicity and is optimal in the least-squares sense. Scikit-learn provides an implementation.
- Monotonic Splines: This method fits a smooth spline curve (like a cubic spline) but imposes constraints to ensure the resulting curve is monotonic. SciPy provides functionality for this. This often results in a smoother curve than PAVA but is an approximation to the best monotonic fit.
Here's how you can implement both:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.isotonic import IsotonicRegression
from scipy.interpolate import UnivariateSpline
# For demonstration of curve_fit with monotonic functions
from scipy.optimize import curve_fit
# --- 1. Generate Sample Data ---
# Let's create data with an underlying increasing trend + noise
np.random.seed(42)
x = np.linspace(0, 10, 100)
y_true = 2 * x + 5 + np.sin(x * 1.5) * 2 # Underlying non-monotonic trend for illustration
# Introduce some noise that might violate strict monotonicity locally
noise = np.random.normal(0, 2.5, size=x.shape)
y_noisy = y_true + noise
# To ensure we have points that violate strict monotonicity for demonstration
# Let's slightly alter some y values to create downward steps
y_noisy[20:25] -= 5
y_noisy[50:55] -= 3
y_noisy[70:75] += 4 # Add a small upward bump after a dip
# Make sure the data is sorted by x for most algorithms
sort_indices = np.argsort(x)
x = x[sort_indices]
y_noisy = y_noisy[sort_indices]
# --- Plot the noisy data ---
plt.figure(figsize=(12, 8))
plt.plot(x, y_noisy, 'o', label='Noisy Data', markersize=5)
plt.title('Sample Data (Potentially Non-Monotonic due to Noise)')
plt.xlabel('X')
plt.ylabel('Y')
plt.grid(True)
# --- 2. Method 1: Isotonic Regression (PAVA) ---
# This guarantees the best least-squares monotonic fit.
# Assumes a non-decreasing relationship by default.
iso_reg = IsotonicRegression(out_of_bounds="clip") # Use "clip" or "nan"
# Note: IsotonicRegression works best if y is roughly ordered, but it handles
# violations internally. Sorting x is still good practice.
# Fit the model
# The fit method expects y values. It implicitly uses the indices (0 to n-1) as x.
# We need to provide the actual x values if they are not uniformly spaced or start from 0.
# A common way is to use the sorted x values directly.
y_iso = iso_reg.fit_transform(x, y_noisy) # Fit using x and y_noisy
plt.plot(x, y_iso, label='Isotonic Regression (PAVA)', linewidth=2, color='red')
print("Isotonic Regression fitted.")
# --- 3. Method 2: Monotonic Spline ---
# This fits a smooth curve that is constrained to be monotonic.
# We need to choose a smoothing factor 's'.
# s = 0 means the spline passes through all points (likely wiggly if noisy).
# Larger s means smoother curve, potentially deviating more from the data.
# Let's try a moderate value, or let UnivariateSpline estimate it.
# Option A: Let UnivariateSpline estimate 's' (often a good starting point)
# mono_spline = UnivariateSpline(x, y_noisy, monotone=True)
# Option B: Specify 's'. We might need to experiment.
# Let's try s roughly equal to the number of data points as a heuristic
# Or relate it to the variance of the noise.
# A value around len(x) * np.var(y_noisy) * 0.01 might be a starting point
# Let's try a fixed value first
s_value = 150 # Experiment with this value!
mono_spline = UnivariateSpline(x, y_noisy, s=s_value, monotone=True)
# Generate y values from the spline
y_spline = mono_spline(x)
plt.plot(x, y_spline, label=f'Monotonic Spline (s={s_value})', linewidth=2, color='green')
print(f"Monotonic Spline fitted with s={s_value}.")
# --- Verification (Optional): Check monotonicity ---
print("\nChecking monotonicity:")
# Isotonic Regression result
is_iso_monotonic = np.all(np.diff(y_iso) >= 0)
print(f"Isotonic Regression output is non-decreasing: {is_iso_monotonic}")
# Monotonic Spline result
is_spline_monotonic = np.all(np.diff(y_spline) >= 0)
print(f"Monotonic Spline output is non-decreasing: {is_spline_monotonic}")
# --- Optional: Fitting Inherently Monotonic Functions (e.g., Exponential) ---
# If you know your data follows a specific *inherently* monotonic function shape,
# you can use curve_fit and rely on the function's nature.
def exponential_func(x, a, b, c):
# Example: a * exp(b * x) + c (monotonic if b > 0)
return a * np.exp(b * x) + c
try:
# Provide bounds to help ensure monotonicity (e.g., b > 0)
# Filter data slightly to reduce noise impact, especially if using strict functions
x_filtered = x[::5] # Use fewer points for simpler models
y_filtered = y_noisy[::5]
# Use parameters known to be roughly monotonic (e.g., positive growth rate 'b')
initial_guess = [1, 0.1, 1] # a, b, c
bounds = ([-np.inf, 0, -np.inf], [np.inf, np.inf, np.inf]) # Ensure b >= 0
params, cov = curve_fit(exponential_func, x_filtered, y_filtered, p0=initial_guess, bounds=bounds, maxfev=5000)
a_fit, b_fit, c_fit = params
# Ensure the fitted parameter b is indeed non-negative (due to bounds/optimization)
if b_fit >= 0:
y_exp = exponential_func(x, a_fit, b_fit, c_fit)
plt.plot(x, y_exp, label=f'Exponential Fit (a={a_fit:.2f}, b={b_fit:.2f})', linewidth=2, color='purple', linestyle='--')
print(f"\nExponential fit successful: a={a_fit:.2f}, b={b_fit:.2f}, c={b_fit:.2f}")
is_exp_monotonic = True # Function is inherently monotonic for b>=0
else:
print("\nExponential fit failed to find a non-decreasing parameter 'b'.")
is_exp_monotonic = False
except RuntimeError:
print("\nCould not find a good exponential fit.")
except ValueError as e:
print(f"\nValue error during exponential fit: {e}")
# Add labels and legend, finalize plot
plt.legend()
plt.ylim(min(y_noisy) - 5, max(y_noisy) + 5) # Adjust y-limits for better visualization
plt.show()
Explanation:
- Sample Data: We create
x and y_noisy. The y_true shows a generally increasing trend but includes a sine wave making it non-monotonic. The noise and manual adjustments create local violations of monotonicity (dips). Sorting the data by x is crucial for many algorithms.
- Isotonic Regression (
sklearn.isotonic.IsotonicRegression):
- We initialize
IsotonicRegression. out_of_bounds="clip" is often useful.
fit_transform(x, y_noisy) calculates the isotonic fit. Internally, it uses the Pool Adjacent Violators Algorithm (PAVA).
- The output
y_iso represents the best least-squares fit that is guaranteed to be non-decreasing with respect to x. Notice it might look like a series of flat steps followed by increases.
- Monotonic Spline (
scipy.interpolate.UnivariateSpline):
- We use
UnivariateSpline with the monotone=True argument.
- The
s parameter controls the trade-off between smoothness and fitting the data closely. s=0 forces the spline through every point, which is bad with noisy data. A larger s results in a smoother curve but might deviate more. Finding a good s often requires experimentation or heuristics (e.g., relating s to the number of points and noise variance).
- The output
y_spline is a smooth curve. It approximates a monotonic fit, ensuring the derivative is non-negative.
- Optional:
curve_fit:
- If you have a strong prior belief about the shape of the monotonic curve (e.g., exponential growth, logistic growth), you can use
scipy.optimize.curve_fit.
- Monotonicity must be guaranteed by the functional form itself (e.g., y is monotonic if or ).
Which method to choose?
- Use Isotonic Regression (PAVA) if:
- You need the guaranteed best least-squares fit among monotonic functions.
- A step-function-like output is acceptable.
- You don't necessarily need a smooth curve.
- Use Monotonic Splines if:
- You need a smooth monotonic curve.
- An approximation to the best monotonic fit is sufficient.
- You are willing to tune the smoothing factor
s.
Remember to adjust the s value for UnivariateSpline based on your specific data and desired smoothness.