
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/example_logistic_group_lasso.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

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

        Click :ref:`here <sphx_glr_download_auto_examples_example_logistic_group_lasso.py>`
        to download the full example code

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_auto_examples_example_logistic_group_lasso.py:


GroupLasso for logistic regression
==================================

A sample script for group lasso regression

.. GENERATED FROM PYTHON SOURCE LINES 9-11

Setup
-----

.. GENERATED FROM PYTHON SOURCE LINES 11-21

.. code-block:: default


    import matplotlib.pyplot as plt
    import numpy as np

    from group_lasso import LogisticGroupLasso

    np.random.seed(0)
    LogisticGroupLasso.LOG_LOSSES = True









.. GENERATED FROM PYTHON SOURCE LINES 22-24

Set dataset parameters
----------------------

.. GENERATED FROM PYTHON SOURCE LINES 24-32

.. code-block:: default

    group_sizes = [np.random.randint(10, 20) for i in range(50)]
    active_groups = [np.random.randint(2) for _ in group_sizes]
    groups = np.concatenate([size * [i] for i, size in enumerate(group_sizes)])
    num_coeffs = sum(group_sizes)
    num_datapoints = 10000
    noise_std = 1









.. GENERATED FROM PYTHON SOURCE LINES 33-35

Generate data matrix
--------------------

.. GENERATED FROM PYTHON SOURCE LINES 35-38

.. code-block:: default

    X = np.random.standard_normal((num_datapoints, num_coeffs))









.. GENERATED FROM PYTHON SOURCE LINES 39-41

Generate coefficients
---------------------

.. GENERATED FROM PYTHON SOURCE LINES 41-52

.. code-block:: default

    w = np.concatenate(
        [
            np.random.standard_normal(group_size) * is_active
            for group_size, is_active in zip(group_sizes, active_groups)
        ]
    )
    w = w.reshape(-1, 1)
    true_coefficient_mask = w != 0
    intercept = 2









.. GENERATED FROM PYTHON SOURCE LINES 53-55

Generate regression targets
---------------------------

.. GENERATED FROM PYTHON SOURCE LINES 55-62

.. code-block:: default

    y_true = X @ w + intercept
    y = y_true + np.random.randn(*y_true.shape) * noise_std
    p = 1 / (1 + np.exp(-y))
    p_true = 1 / (1 + np.exp(-y_true))
    c = np.random.binomial(1, p_true)









.. GENERATED FROM PYTHON SOURCE LINES 63-65

View noisy data and compute maximum accuracy
--------------------------------------------

.. GENERATED FROM PYTHON SOURCE LINES 65-74

.. code-block:: default

    plt.figure()
    plt.plot(p, p_true, ".")
    plt.xlabel("Noisy probabilities")
    plt.ylabel("Noise-free probabilities")
    # Use noisy y as true because that is what we would have access
    # to in a real-life setting.
    best_accuracy = ((p_true > 0.5) == c).mean()





.. image:: /auto_examples/images/sphx_glr_example_logistic_group_lasso_001.png
    :alt: example logistic group lasso
    :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 75-77

Generate estimator and train it
-------------------------------

.. GENERATED FROM PYTHON SOURCE LINES 77-89

.. code-block:: default

    gl = LogisticGroupLasso(
        groups=groups,
        group_reg=0.05,
        l1_reg=0,
        scale_reg="inverse_group_size",
        subsampling_scheme=1,
        supress_warning=True,
    )

    gl.fit(X, c)






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

 Out:

 .. code-block:: none

    /home/yngve/Dropbox/Programming/group-lasso/src/group_lasso/_group_lasso.py:838: UserWarning: Subsampling is not stable for logistic regression group lasso.
      warnings.warn(
    /home/yngve/Dropbox/Programming/group-lasso/src/group_lasso/_fista.py:114: ConvergenceWarning: The FISTA iterations did not converge to a sufficient minimum.
    You used subsampling then this is expected, otherwise, try increasing the number of iterations or decreasing the tolerance.
      warnings.warn(

    LogisticGroupLasso(groups=array([ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,
            1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  2,  2,
            2,  2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,
            4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
            5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
            5,  5,  6,  6,  6,  6,  6,  6,  6,  6,  6,  6,  6,  6,  6,  7,  7,
            7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  7,  8,  8,  8,  8,
            8,  8,  8,  8,  8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9,  9,
            9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10...
           43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 44,
           44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 45, 45, 45, 45, 45, 45,
           45, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
           46, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47,
           47, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 49, 49,
           49, 49, 49, 49, 49, 49]),
                       l1_reg=0, scale_reg='inverse_group_size',
                       subsampling_scheme=1, supress_warning=True)



.. GENERATED FROM PYTHON SOURCE LINES 90-92

Extract results and compute performance metrics
-----------------------------------------------

.. GENERATED FROM PYTHON SOURCE LINES 92-107

.. code-block:: default


    # Extract info from estimator
    pred_c = gl.predict(X)
    sparsity_mask = gl.sparsity_mask_
    w_hat = gl.coef_

    # Compute performance metrics
    accuracy = (pred_c == c).mean()

    # Print results
    print(f"Number variables: {len(sparsity_mask)}")
    print(f"Number of chosen variables: {sparsity_mask.sum()}")
    print(f"Accuracy: {accuracy}, best possible accuracy = {best_accuracy}")






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

 Out:

 .. code-block:: none

    Number variables: 720
    Number of chosen variables: 295
    Accuracy: 0.504607, best possible accuracy = 0.9698




.. GENERATED FROM PYTHON SOURCE LINES 108-110

Visualise regression coefficients
---------------------------------

.. GENERATED FROM PYTHON SOURCE LINES 110-127

.. code-block:: default

    coef = gl.coef_[:, 1] - gl.coef_[:, 0]
    plt.figure()
    plt.plot(w / np.linalg.norm(w), ".", label="True weights")
    plt.plot(
        coef / np.linalg.norm(coef), ".", label="Estimated weights",
    )

    plt.figure()
    plt.plot([w.min(), w.max()], [coef.min(), coef.max()], "gray")
    plt.scatter(w, coef, s=10)
    plt.ylabel("Learned coefficients")
    plt.xlabel("True coefficients")

    plt.figure()
    plt.plot(gl.losses_)

    plt.show()



.. rst-class:: sphx-glr-horizontal


    *

      .. image:: /auto_examples/images/sphx_glr_example_logistic_group_lasso_002.png
          :alt: example logistic group lasso
          :class: sphx-glr-multi-img

    *

      .. image:: /auto_examples/images/sphx_glr_example_logistic_group_lasso_003.png
          :alt: example logistic group lasso
          :class: sphx-glr-multi-img

    *

      .. image:: /auto_examples/images/sphx_glr_example_logistic_group_lasso_004.png
          :alt: example logistic group lasso
          :class: sphx-glr-multi-img






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

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


.. _sphx_glr_download_auto_examples_example_logistic_group_lasso.py:


.. only :: html

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



  .. container:: sphx-glr-download sphx-glr-download-python

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



  .. container:: sphx-glr-download sphx-glr-download-jupyter

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


.. only:: html

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

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