Curve fitting#

This example shows how to use pysolve-gn package.

We will fit an exponential curve to noisy data.

Define the model function#

Lets consider the following exponential model.

\[y = a \cdot e^{b x}\]

We generate a small and noisy dataset. In this situation, the fitted parameters can deviate significantly from the true parameters.

The parameters \(a\) and \(b\) will be estimated from the noisy data.

import numpy as np
import matplotlib.pyplot as plt
import pysolvegn

np.random.seed(0)


def model(params, x):
    a, b = params
    return a * np.exp(b * x)


n_points = 100
x_data = np.linspace(0, 3, n_points)

true_params = np.array([2.5, 0.5])

y_true = model(true_params, x_data)

# Add a relatively strong noise to the observations.
y_data = y_true + 1.0 * np.random.normal(size=y_true.shape)

Create the data term#

The data term represents the residuals between the observations and the model predictions.

\[r_j(\mathbf{p}) = a e^{b x_j} - y_j\]

The Jacobian is:

\[\frac{\partial r_j}{\partial a} = e^{b x_j}\]
\[\frac{\partial r_j}{\partial b} = a x_j e^{b x_j}\]

See also

The class pysolvegn.Term to store the residual and jacobian functions.

def residual_function(params):
    return model(params, x_data) - y_data


def jacobian_function(params):
    a, b = params

    J = np.zeros((len(x_data), len(params)))

    J[:, 0] = np.exp(b * x_data)
    J[:, 1] = a * x_data * np.exp(b * x_data)

    return J


data_term = pysolvegn.Term.from_rJ(
    residual_func=residual_function,
    jacobian_func=jacobian_function,
    loss="linear",
    weight=1.0,
)

Performing optimization#

We solve the problem using only the pysolvegn.solve() function. This function takes the data term, an initialisation and convergence criteria.

The function returns a pysolvegn.SolveResult object containing the optimized parameters (result.parameters) and information about the optimization: result.success indicates whether a convergence criterion was satisfied, and result.message describes why the optimization stopped.

initial_params = np.array([1.0, 1.0])

result = pysolvegn.solve(
    terms=data_term,
    p0=initial_params,
    max_iteration=100,
    xtol=1e-8,
    ftol=1e-8,
    verbosity=2,
)

optimized_parameters = result.parameters
Individual costs [rJ term]: C_i = 0.5 * ρ(||r_i||^2)
Cost: C = sum(w_i * C_i)
Step norm: ||Δp||
Optimality: ||g||

Iteration  Total time (s)      Cost C            ΔC           ||Δp||_2         ||g||_∞
    0         6.172e-05       4.287e+02                                       5.101e+03
    1         1.793e-04       9.622e+01      -3.325e+02       8.856e-01       9.936e+02
    2         2.601e-04       5.346e+01      -4.277e+01       6.382e-01       3.246e+02
    3         3.226e-04       5.072e+01      -2.738e+00       4.633e-02       4.134e+00
    4         3.819e-04       5.072e+01      -6.618e-04       2.843e-03       4.314e-02
    5         4.381e-04       5.072e+01      -3.914e-07       1.021e-04       2.567e-03
[ftol] Convergence achieved: 0 <= F_previous - F < ftol * F with ftol = 1e-08.

Display the fitted parameters#

print("Success:", result.success)
print("Message:", result.message)
print("Number of iterations:", result.n_iterations)
print("Final cost:", result.cost)

print("\nTrue parameters:")
print(true_params)

print("\nEstimated parameters:")
print(optimized_parameters)

x_plot = np.linspace(0, 3, 300)
y_plot = model(optimized_parameters, x_plot)
y_true_plot = model(true_params, x_plot)

plt.figure(figsize=(10, 6))

plt.scatter(
    x_data,
    y_data,
    label="Data Points",
    color="red",
    s=35,
)

plt.plot(
    x_plot,
    y_true_plot,
    label="True Curve",
    color="blue",
    linewidth=2,
)

plt.plot(
    x_plot,
    y_plot,
    label="Optimized Curve",
    color="orange",
    linestyle="--",
    linewidth=2,
)

plt.title("Curve Fitting")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.grid()

plt.show()
Curve Fitting
Success: True
Message: [ftol] Convergence achieved: 0 <= F_previous - F < ftol * F with ftol = 1e-08.
Number of iterations: 5
Final cost: 50.716550445680085

True parameters:
[2.5 0.5]

Estimated parameters:
[2.45861374 0.51137177]

Total running time of the script: (0 minutes 0.047 seconds)

Gallery generated by Sphinx-Gallery