Skip to content
TheChatArchiveThe Chat Archive
Hunyuanhunyuan-turbos-20250416· TencentHugging Face LMArena Human Preference 140K

Fit monotonic curve to data in python

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-flash-lite-preview-06-17-thinking’s answer.
  1. User

    Fit monotonic curve to data in python

  2. Hunyuan 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, and sklearn:


    ✅ Method 1: Using scipy.interpolate.PchipInterpolator

    PCHIP (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 + constraints

    This 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

    MethodTypeProsCons
    PchipInterpolatorInterpolationSmooth, preserves monotonicityMay overshoot if noisy
    IsotonicRegressionRegressionNon-parametric, fastPiecewise constant, not smooth
    CubicSpline + constraintsSmooth splineVery flexible (if coded well)More complex to implement

    Would you like help fitting a smooth monotonic curve (like a spline) with explicit constraints?

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.