Quick Start - Increasing Cubic Spline

This first example demonstrates how to use a cubic spline with a monotonicity constraint.

Complete Code

examples/quick_start.py
    import numpy as np
    from BsplineQuantRegpy import SplineCubicQuant
    import matplotlib.pyplot as plt

    # Generate data
    x = np.linspace(0, 1, 100)
    y = 3*x + 0.2*np.sin(10*np.pi*x) + 0.2*np.random.randn(100)
    knots = np.quantile(x, np.linspace(0, 1, 11))

    # Fit with monotonicity constraint
    result = SplineCubicQuant(x, y, knots, tau=0.5, monot=1)
    # Fit without monotonicity constraint (uncomment to test)
    #result = SplineCubicQuant(x, y, knots, tau=0.5, monot=0)
    # Evaluate
    x_eval = np.linspace(0, 1, 200)
    y_eval = result(x_eval)

    plt.plot(x,y,"*r")
    plt.plot(x_eval,y_eval,color='black')
    plt.show()

Explanation

  1. Import: We import SplineCubicQuant for regression with cubic splines.

  2. Data Generation: - 100 points on the interval [0, 1] - The target function is \(3x + 0.2\sin(10\pi x)\) with noise

  3. Knot Definition: 11 knots placed at the quantiles of x

  4. Fitting: Call to SplineCubicQuant with monot=1 to enforce an increasing constraint

  5. Visualization: Display of data and fitted curve

Result

The execution produces a plot showing the data in red and the fitted spline in black, respecting the monotonicity constraint.

To try without constraints

Uncomment the line: .. code-block:: python

#result = SplineCubicQuant(x, y, knots, tau=0.5, monot=0)