.. note::
    :class: sphx-glr-download-link-note

    Click :ref:`here <sphx_glr_download_auto_examples_example_linear_regression.py>` to download the full example code
.. rst-class:: sphx-glr-example-title

.. _sphx_glr_auto_examples_example_linear_regression.py:


.. _tut_linear_regression:

Train a linear regression potential
===================================

In this tutorial, we train a linear regression model on the descriptors obtained using the
symmetry functions.


.. code-block:: default


    from kliff.descriptors import SymmetryFunction
    from kliff.dataset import Dataset
    from kliff.models import LinearRegression
    from kliff.calculators import CalculatorTorch


    descriptor = SymmetryFunction(
        cut_name='cos', cut_dists={'Si-Si': 5.0}, hyperparams='set30', normalize=True
    )


    model = LinearRegression(descriptor)

    # training set
    dataset_name = 'Si_training_set/varying_alat'
    tset = Dataset()
    tset.read(dataset_name)
    configs = tset.get_configs()
    print('Number of configurations:', len(configs))

    # calculator
    calc = CalculatorTorch(model)
    calc.create(configs, reuse=True)






.. rst-class:: sphx-glr-script-out

 Out:

 .. code-block:: none

    Number of configurations: 400
    Start generating fingerprints
    Finish generating fingerprints



We can train a linear regression model by minimizing a loss function as discussed in
:ref:`tut_nn`. But linear regression model has analytic solutions, and thus we can train
the model directly by using this feature. This can be achieved by calling the ``fit()``
function of its calculator.



.. code-block:: default


    # fit the model
    calc.fit()


    # save model
    model.save('linear_model.pkl')




.. rst-class:: sphx-glr-script-out

 Out:

 .. code-block:: none

    fit model "LinearRegression" finished.




.. rst-class:: sphx-glr-timing

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


.. _sphx_glr_download_auto_examples_example_linear_regression.py:


.. only :: html

 .. container:: sphx-glr-footer
    :class: sphx-glr-footer-example



  .. container:: sphx-glr-download

     :download:`Download Python source code: example_linear_regression.py <example_linear_regression.py>`



  .. container:: sphx-glr-download

     :download:`Download Jupyter notebook: example_linear_regression.ipynb <example_linear_regression.ipynb>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
