.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "../../docs/source/_gallery/adding_regularization.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_.._.._docs_source__gallery_adding_regularization.py: .. _sphx_glr__gallery_adding_regularization.py: Adding regularization (curve fitting) ====================================== This example shows how to use regularization with pysolve-gn. This example is the continuation of the basic curve fitting example, demonstrating how to incorporate regularization. .. GENERATED FROM PYTHON SOURCE LINES 14-29 Copy the basic curve fitting example --------------------------------------- Lets consider the following exponential model. .. math:: 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 :math:`a` and :math:`b` will be estimated from the noisy data. A Gaussian prior will then be used to regularize the solution. .. GENERATED FROM PYTHON SOURCE LINES 29-76 .. code-block:: Python 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 relatively strong noise and bias to make the effect of regularization visible. y_data = y_true + 1.2 * np.random.normal(size=y_true.shape) 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, ) .. GENERATED FROM PYTHON SOURCE LINES 77-111 Define a Gaussian regularization --------------------------------- We can add a Gaussian prior on the parameters. The regularization will be added as an additional term (:class:`pysolvegn.Term`) in the optimization problem. The regularization residuals are: .. math:: r_{\mathrm{reg},i} = \frac{p_i - \mu_i}{\sigma_i} where :math:`\mu_i` is the expected value of the parameter and :math:`\sigma_i` controls the strength of the prior. The corresponding contribution to the cost is: .. math:: \frac{1}{2} \sum_i \left( \frac{p_i-\mu_i}{\sigma_i} \right)^2 Here we assume that the parameters are expected to be close to :math:`[2.5, 0.5]`, but we allow some uncertainty around these values. .. note:: This regularization term can be defined similarly to the data term, given a residual function and a Jacobian function or directly using the provided helper function :func:`pysolvegn.build_squared_regularization`. .. GENERATED FROM PYTHON SOURCE LINES 111-121 .. code-block:: Python prior_means = np.array([2.4, 0.5]) prior_stds = np.array([0.5, 0.2]) regularization_term = pysolvegn.build_squared_regularization( means=prior_means, stds=prior_stds, weight=0.1 * y_data.size ** 2, # Can be changed to update the regularization strength ) .. GENERATED FROM PYTHON SOURCE LINES 122-146 Fit with regularization ----------------------- The regularization is simply added as another term in the optimization problem. The solver therefore minimizes: .. math:: C(\mathbf{p}) = \frac{1}{2}\sum_j r_j(\mathbf{p})^2 + \frac{1}{2}w \sum_i \left( \frac{p_i-\mu_i}{\sigma_i} \right)^2 Both the data term and the regularization term contribute to the Gauss-Newton system. :func:`pysolvegn.solve` returns a :class:`pysolvegn.SolveResult`: the optimized parameters are stored in ``result.parameters``. .. GENERATED FROM PYTHON SOURCE LINES 146-171 .. code-block:: Python result_without_regularization = pysolvegn.solve( terms=[ data_term, ], p0=np.array([1.0, 1.0]), max_iteration=100, xtol=1e-8, ftol=1e-8, verbosity=0, ) result_with_regularization = pysolvegn.solve( terms=[ data_term, regularization_term, ], p0=np.array([1.0, 1.0]), max_iteration=100, xtol=1e-8, ftol=1e-8, verbosity=0, ) .. GENERATED FROM PYTHON SOURCE LINES 172-174 Display the fitted parameters ------------------------------ .. GENERATED FROM PYTHON SOURCE LINES 174-242 .. code-block:: Python print("True parameters:") print(true_params) print("\nEstimated parameters without regularization:") print(result_without_regularization.parameters) print("Success:", result_without_regularization.success) print("\nEstimated parameters with regularization:") print(result_with_regularization.parameters) print("Success:", result_with_regularization.success) # Use a dense set of points to display the fitted curves smoothly. x_plot = np.linspace(0, 3, 300) y_true_plot = model(true_params, x_plot) y_without_regularization_plot = model( result_without_regularization.parameters, x_plot, ) y_with_regularization_plot = model( result_with_regularization.parameters, 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_without_regularization_plot, label="Without Regularization", color="orange", linestyle="--", linewidth=2, ) plt.plot( x_plot, y_with_regularization_plot, label="With Regularization", color="green", linestyle="-.", linewidth=2, ) plt.title("Curve Fitting with Gaussian Regularization") plt.xlabel("x") plt.ylabel("y") plt.legend() plt.grid() plt.show() .. image-sg:: /_gallery/images/sphx_glr_adding_regularization_001.png :alt: Curve Fitting with Gaussian Regularization :srcset: /_gallery/images/sphx_glr_adding_regularization_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none True parameters: [2.5 0.5] Estimated parameters without regularization: [2.449387 0.513832] Success: True Estimated parameters with regularization: [2.410583 0.509229] Success: True .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.051 seconds) .. _sphx_glr_download_.._.._docs_source__gallery_adding_regularization.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: adding_regularization.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: adding_regularization.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: adding_regularization.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_