.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/inspection/plot_linear_model_coefficient_interpretation.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end <sphx_glr_download_auto_examples_inspection_plot_linear_model_coefficient_interpretation.py>` to download the full example code or to run this example in your browser via JupyterLite or Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_inspection_plot_linear_model_coefficient_interpretation.py: ====================================================================== Common pitfalls in the interpretation of coefficients of linear models ====================================================================== In linear models, the target value is modeled as a linear combination of the features (see the :ref:`linear_model` User Guide section for a description of a set of linear models available in scikit-learn). Coefficients in multiple linear models represent the relationship between the given feature, :math:`X_i` and the target, :math:`y`, assuming that all the other features remain constant (`conditional dependence <https://en.wikipedia.org/wiki/Conditional_dependence>`_). This is different from plotting :math:`X_i` versus :math:`y` and fitting a linear relationship: in that case all possible values of the other features are taken into account in the estimation (marginal dependence). This example will provide some hints in interpreting coefficient in linear models, pointing at problems that arise when either the linear model is not appropriate to describe the dataset, or when features are correlated. .. note:: Keep in mind that the features :math:`X` and the outcome :math:`y` are in general the result of a data generating process that is unknown to us. Machine learning models are trained to approximate the unobserved mathematical function that links :math:`X` to :math:`y` from sample data. As a result, any interpretation made about a model may not necessarily generalize to the true data generating process. This is especially true when the model is of bad quality or when the sample data is not representative of the population. We will use data from the `"Current Population Survey" <https://www.openml.org/d/534>`_ from 1985 to predict wage as a function of various features such as experience, age, or education. .. contents:: :local: :depth: 1 .. GENERATED FROM PYTHON SOURCE LINES 43-49 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy as sp import seaborn as sns .. GENERATED FROM PYTHON SOURCE LINES 50-56 The dataset: wages ------------------ We fetch the data from `OpenML <http://openml.org/>`_. Note that setting the parameter `as_frame` to True will retrieve the data as a pandas dataframe. .. GENERATED FROM PYTHON SOURCE LINES 56-60 .. code-block:: Python from sklearn.datasets import fetch_openml survey = fetch_openml(data_id=534, as_frame=True) .. GENERATED FROM PYTHON SOURCE LINES 61-63 Then, we identify features `X` and targets `y`: the column WAGE is our target variable (i.e., the variable which we want to predict). .. GENERATED FROM PYTHON SOURCE LINES 63-67 .. code-block:: Python X = survey.data[survey.feature_names] X.describe(include="all") .. raw:: html <div class="output_subarea output_html rendered_html output_result"> <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>EDUCATION</th> <th>SOUTH</th> <th>SEX</th> <th>EXPERIENCE</th> <th>UNION</th> <th>AGE</th> <th>RACE</th> <th>OCCUPATION</th> <th>SECTOR</th> <th>MARR</th> </tr> </thead> <tbody> <tr> <th>count</th> <td>534.000000</td> <td>534</td> <td>534</td> <td>534.000000</td> <td>534</td> <td>534.000000</td> <td>534</td> <td>534</td> <td>534</td> <td>534</td> </tr> <tr> <th>unique</th> <td>NaN</td> <td>2</td> <td>2</td> <td>NaN</td> <td>2</td> <td>NaN</td> <td>3</td> <td>6</td> <td>3</td> <td>2</td> </tr> <tr> <th>top</th> <td>NaN</td> <td>no</td> <td>male</td> <td>NaN</td> <td>not_member</td> <td>NaN</td> <td>White</td> <td>Other</td> <td>Other</td> <td>Married</td> </tr> <tr> <th>freq</th> <td>NaN</td> <td>378</td> <td>289</td> <td>NaN</td> <td>438</td> <td>NaN</td> <td>440</td> <td>156</td> <td>411</td> <td>350</td> </tr> <tr> <th>mean</th> <td>13.018727</td> <td>NaN</td> <td>NaN</td> <td>17.822097</td> <td>NaN</td> <td>36.833333</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>std</th> <td>2.615373</td> <td>NaN</td> <td>NaN</td> <td>12.379710</td> <td>NaN</td> <td>11.726573</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>min</th> <td>2.000000</td> <td>NaN</td> <td>NaN</td> <td>0.000000</td> <td>NaN</td> <td>18.000000</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>25%</th> <td>12.000000</td> <td>NaN</td> <td>NaN</td> <td>8.000000</td> <td>NaN</td> <td>28.000000</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>50%</th> <td>12.000000</td> <td>NaN</td> <td>NaN</td> <td>15.000000</td> <td>NaN</td> <td>35.000000</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>75%</th> <td>15.000000</td> <td>NaN</td> <td>NaN</td> <td>26.000000</td> <td>NaN</td> <td>44.000000</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>max</th> <td>18.000000</td> <td>NaN</td> <td>NaN</td> <td>55.000000</td> <td>NaN</td> <td>64.000000</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> </tbody> </table> </div> </div> <br /> <br /> .. GENERATED FROM PYTHON SOURCE LINES 68-71 Note that the dataset contains categorical and numerical variables. We will need to take this into account when preprocessing the dataset thereafter. .. GENERATED FROM PYTHON SOURCE LINES 71-74 .. code-block:: Python X.head() .. raw:: html <div class="output_subarea output_html rendered_html output_result"> <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>EDUCATION</th> <th>SOUTH</th> <th>SEX</th> <th>EXPERIENCE</th> <th>UNION</th> <th>AGE</th> <th>RACE</th> <th>OCCUPATION</th> <th>SECTOR</th> <th>MARR</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>8</td> <td>no</td> <td>female</td> <td>21</td> <td>not_member</td> <td>35</td> <td>Hispanic</td> <td>Other</td> <td>Manufacturing</td> <td>Married</td> </tr> <tr> <th>1</th> <td>9</td> <td>no</td> <td>female</td> <td>42</td> <td>not_member</td> <td>57</td> <td>White</td> <td>Other</td> <td>Manufacturing</td> <td>Married</td> </tr> <tr> <th>2</th> <td>12</td> <td>no</td> <td>male</td> <td>1</td> <td>not_member</td> <td>19</td> <td>White</td> <td>Other</td> <td>Manufacturing</td> <td>Unmarried</td> </tr> <tr> <th>3</th> <td>12</td> <td>no</td> <td>male</td> <td>4</td> <td>not_member</td> <td>22</td> <td>White</td> <td>Other</td> <td>Other</td> <td>Unmarried</td> </tr> <tr> <th>4</th> <td>12</td> <td>no</td> <td>male</td> <td>17</td> <td>not_member</td> <td>35</td> <td>White</td> <td>Other</td> <td>Other</td> <td>Married</td> </tr> </tbody> </table> </div> </div> <br /> <br /> .. GENERATED FROM PYTHON SOURCE LINES 75-77 Our target for prediction: the wage. Wages are described as floating-point number in dollars per hour. .. GENERATED FROM PYTHON SOURCE LINES 79-82 .. code-block:: Python y = survey.target.values.ravel() survey.target.head() .. rst-class:: sphx-glr-script-out .. code-block:: none 0 5.10 1 4.95 2 6.67 3 4.00 4 7.50 Name: WAGE, dtype: float64 .. GENERATED FROM PYTHON SOURCE LINES 83-88 We split the sample into a train and a test dataset. Only the train dataset will be used in the following exploratory analysis. This is a way to emulate a real situation where predictions are performed on an unknown target, and we don't want our analysis and decisions to be biased by our knowledge of the test data. .. GENERATED FROM PYTHON SOURCE LINES 88-93 .. code-block:: Python from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) .. GENERATED FROM PYTHON SOURCE LINES 94-99 First, let's get some insights by looking at the variable distributions and at the pairwise relationships between them. Only numerical variables will be used. In the following plot, each dot represents a sample. .. _marginal_dependencies: .. GENERATED FROM PYTHON SOURCE LINES 99-104 .. code-block:: Python train_dataset = X_train.copy() train_dataset.insert(0, "WAGE", y_train) _ = sns.pairplot(train_dataset, kind="reg", diag_kind="kde") .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_001.png :alt: plot linear model coefficient interpretation :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 105-124 Looking closely at the WAGE distribution reveals that it has a long tail. For this reason, we should take its logarithm to turn it approximately into a normal distribution (linear models such as ridge or lasso work best for a normal distribution of error). The WAGE is increasing when EDUCATION is increasing. Note that the dependence between WAGE and EDUCATION represented here is a marginal dependence, i.e., it describes the behavior of a specific variable without keeping the others fixed. Also, the EXPERIENCE and AGE are strongly linearly correlated. .. _the-pipeline: The machine-learning pipeline ----------------------------- To design our machine-learning pipeline, we first manually check the type of data that we are dealing with: .. GENERATED FROM PYTHON SOURCE LINES 124-127 .. code-block:: Python survey.data.info() .. rst-class:: sphx-glr-script-out .. code-block:: none <class 'pandas.core.frame.DataFrame'> RangeIndex: 534 entries, 0 to 533 Data columns (total 10 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 EDUCATION 534 non-null int64 1 SOUTH 534 non-null category 2 SEX 534 non-null category 3 EXPERIENCE 534 non-null int64 4 UNION 534 non-null category 5 AGE 534 non-null int64 6 RACE 534 non-null category 7 OCCUPATION 534 non-null category 8 SECTOR 534 non-null category 9 MARR 534 non-null category dtypes: category(7), int64(3) memory usage: 17.2 KB .. GENERATED FROM PYTHON SOURCE LINES 128-139 As seen previously, the dataset contains columns with different data types and we need to apply a specific preprocessing for each data types. In particular categorical variables cannot be included in linear model if not coded as integers first. In addition, to avoid categorical features to be treated as ordered values, we need to one-hot-encode them. Our pre-processor will - one-hot encode (i.e., generate a column by category) the categorical columns, only for non-binary categorical variables; - as a first approach (we will see after how the normalisation of numerical values will affect our discussion), keep numerical values as they are. .. GENERATED FROM PYTHON SOURCE LINES 139-152 .. code-block:: Python from sklearn.compose import make_column_transformer from sklearn.preprocessing import OneHotEncoder categorical_columns = ["RACE", "OCCUPATION", "SECTOR", "MARR", "UNION", "SEX", "SOUTH"] numerical_columns = ["EDUCATION", "EXPERIENCE", "AGE"] preprocessor = make_column_transformer( (OneHotEncoder(drop="if_binary"), categorical_columns), remainder="passthrough", verbose_feature_names_out=False, # avoid to prepend the preprocessor names ) .. GENERATED FROM PYTHON SOURCE LINES 153-155 To describe the dataset as a linear model we use a ridge regressor with a very small regularization and to model the logarithm of the WAGE. .. GENERATED FROM PYTHON SOURCE LINES 155-167 .. code-block:: Python from sklearn.compose import TransformedTargetRegressor from sklearn.linear_model import Ridge from sklearn.pipeline import make_pipeline model = make_pipeline( preprocessor, TransformedTargetRegressor( regressor=Ridge(alpha=1e-10), func=np.log10, inverse_func=sp.special.exp10 ), ) .. GENERATED FROM PYTHON SOURCE LINES 168-172 Processing the dataset ---------------------- First, we fit the model. .. GENERATED FROM PYTHON SOURCE LINES 172-175 .. code-block:: Python model.fit(X_train, y_train) .. raw:: html <div class="output_subarea output_html rendered_html output_result"> <style>#sk-container-id-31 { /* Definition of color scheme common for light and dark mode */ --sklearn-color-text: black; --sklearn-color-line: gray; /* Definition of color scheme for unfitted estimators */ --sklearn-color-unfitted-level-0: #fff5e6; --sklearn-color-unfitted-level-1: #f6e4d2; --sklearn-color-unfitted-level-2: #ffe0b3; --sklearn-color-unfitted-level-3: chocolate; /* Definition of color scheme for fitted estimators */ --sklearn-color-fitted-level-0: #f0f8ff; --sklearn-color-fitted-level-1: #d4ebff; --sklearn-color-fitted-level-2: #b3dbfd; --sklearn-color-fitted-level-3: cornflowerblue; /* Specific color for light theme */ --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black))); --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white))); --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black))); --sklearn-color-icon: #696969; @media (prefers-color-scheme: dark) { /* Redefinition of color scheme for dark theme */ --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white))); --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111))); --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white))); --sklearn-color-icon: #878787; } } #sk-container-id-31 { color: var(--sklearn-color-text); } #sk-container-id-31 pre { padding: 0; } #sk-container-id-31 input.sk-hidden--visually { border: 0; clip: rect(1px 1px 1px 1px); clip: rect(1px, 1px, 1px, 1px); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } #sk-container-id-31 div.sk-dashed-wrapped { border: 1px dashed var(--sklearn-color-line); margin: 0 0.4em 0.5em 0.4em; box-sizing: border-box; padding-bottom: 0.4em; background-color: var(--sklearn-color-background); } #sk-container-id-31 div.sk-container { /* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */ display: inline-block !important; position: relative; } #sk-container-id-31 div.sk-text-repr-fallback { display: none; } div.sk-parallel-item, div.sk-serial, div.sk-item { /* draw centered vertical line to link estimators */ background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background)); background-size: 2px 100%; background-repeat: no-repeat; background-position: center center; } /* Parallel-specific style estimator block */ #sk-container-id-31 div.sk-parallel-item::after { content: ""; width: 100%; border-bottom: 2px solid var(--sklearn-color-text-on-default-background); flex-grow: 1; } #sk-container-id-31 div.sk-parallel { display: flex; align-items: stretch; justify-content: center; background-color: var(--sklearn-color-background); position: relative; } #sk-container-id-31 div.sk-parallel-item { display: flex; flex-direction: column; } #sk-container-id-31 div.sk-parallel-item:first-child::after { align-self: flex-end; width: 50%; } #sk-container-id-31 div.sk-parallel-item:last-child::after { align-self: flex-start; width: 50%; } #sk-container-id-31 div.sk-parallel-item:only-child::after { width: 0; } /* Serial-specific style estimator block */ #sk-container-id-31 div.sk-serial { display: flex; flex-direction: column; align-items: center; background-color: var(--sklearn-color-background); padding-right: 1em; padding-left: 1em; } /* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is clickable and can be expanded/collapsed. - Pipeline and ColumnTransformer use this feature and define the default style - Estimators will overwrite some part of the style using the `sk-estimator` class */ /* Pipeline and ColumnTransformer style (default) */ #sk-container-id-31 div.sk-toggleable { /* Default theme specific background. It is overwritten whether we have a specific estimator or a Pipeline/ColumnTransformer */ background-color: var(--sklearn-color-background); } /* Toggleable label */ #sk-container-id-31 label.sk-toggleable__label { cursor: pointer; display: block; width: 100%; margin-bottom: 0; padding: 0.5em; box-sizing: border-box; text-align: center; } #sk-container-id-31 label.sk-toggleable__label-arrow:before { /* Arrow on the left of the label */ content: "▸"; float: left; margin-right: 0.25em; color: var(--sklearn-color-icon); } #sk-container-id-31 label.sk-toggleable__label-arrow:hover:before { color: var(--sklearn-color-text); } /* Toggleable content - dropdown */ #sk-container-id-31 div.sk-toggleable__content { max-height: 0; max-width: 0; overflow: hidden; text-align: left; /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-31 div.sk-toggleable__content.fitted { /* fitted */ background-color: var(--sklearn-color-fitted-level-0); } #sk-container-id-31 div.sk-toggleable__content pre { margin: 0.2em; border-radius: 0.25em; color: var(--sklearn-color-text); /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-31 div.sk-toggleable__content.fitted pre { /* unfitted */ background-color: var(--sklearn-color-fitted-level-0); } #sk-container-id-31 input.sk-toggleable__control:checked~div.sk-toggleable__content { /* Expand drop-down */ max-height: 200px; max-width: 100%; overflow: auto; } #sk-container-id-31 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before { content: "▾"; } /* Pipeline/ColumnTransformer-specific style */ #sk-container-id-31 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label { color: var(--sklearn-color-text); background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-31 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label { background-color: var(--sklearn-color-fitted-level-2); } /* Estimator-specific style */ /* Colorize estimator box */ #sk-container-id-31 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-31 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label { /* fitted */ background-color: var(--sklearn-color-fitted-level-2); } #sk-container-id-31 div.sk-label label.sk-toggleable__label, #sk-container-id-31 div.sk-label label { /* The background is the default theme color */ color: var(--sklearn-color-text-on-default-background); } /* On hover, darken the color of the background */ #sk-container-id-31 div.sk-label:hover label.sk-toggleable__label { color: var(--sklearn-color-text); background-color: var(--sklearn-color-unfitted-level-2); } /* Label box, darken color on hover, fitted */ #sk-container-id-31 div.sk-label.fitted:hover label.sk-toggleable__label.fitted { color: var(--sklearn-color-text); background-color: var(--sklearn-color-fitted-level-2); } /* Estimator label */ #sk-container-id-31 div.sk-label label { font-family: monospace; font-weight: bold; display: inline-block; line-height: 1.2em; } #sk-container-id-31 div.sk-label-container { text-align: center; } /* Estimator-specific */ #sk-container-id-31 div.sk-estimator { font-family: monospace; border: 1px dotted var(--sklearn-color-border-box); border-radius: 0.25em; box-sizing: border-box; margin-bottom: 0.5em; /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-31 div.sk-estimator.fitted { /* fitted */ background-color: var(--sklearn-color-fitted-level-0); } /* on hover */ #sk-container-id-31 div.sk-estimator:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-31 div.sk-estimator.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-2); } /* Specification for estimator info (e.g. "i" and "?") */ /* Common style for "i" and "?" */ .sk-estimator-doc-link, a:link.sk-estimator-doc-link, a:visited.sk-estimator-doc-link { float: right; font-size: smaller; line-height: 1em; font-family: monospace; background-color: var(--sklearn-color-background); border-radius: 1em; height: 1em; width: 1em; text-decoration: none !important; margin-left: 1ex; /* unfitted */ border: var(--sklearn-color-unfitted-level-1) 1pt solid; color: var(--sklearn-color-unfitted-level-1); } .sk-estimator-doc-link.fitted, a:link.sk-estimator-doc-link.fitted, a:visited.sk-estimator-doc-link.fitted { /* fitted */ border: var(--sklearn-color-fitted-level-1) 1pt solid; color: var(--sklearn-color-fitted-level-1); } /* On hover */ div.sk-estimator:hover .sk-estimator-doc-link:hover, .sk-estimator-doc-link:hover, div.sk-label-container:hover .sk-estimator-doc-link:hover, .sk-estimator-doc-link:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover, .sk-estimator-doc-link.fitted:hover, div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover, .sk-estimator-doc-link.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } /* Span, style for the box shown on hovering the info icon */ .sk-estimator-doc-link span { display: none; z-index: 9999; position: relative; font-weight: normal; right: .2ex; padding: .5ex; margin: .5ex; width: min-content; min-width: 20ex; max-width: 50ex; color: var(--sklearn-color-text); box-shadow: 2pt 2pt 4pt #999; /* unfitted */ background: var(--sklearn-color-unfitted-level-0); border: .5pt solid var(--sklearn-color-unfitted-level-3); } .sk-estimator-doc-link.fitted span { /* fitted */ background: var(--sklearn-color-fitted-level-0); border: var(--sklearn-color-fitted-level-3); } .sk-estimator-doc-link:hover span { display: block; } /* "?"-specific style due to the `<a>` HTML tag */ #sk-container-id-31 a.estimator_doc_link { float: right; font-size: 1rem; line-height: 1em; font-family: monospace; background-color: var(--sklearn-color-background); border-radius: 1rem; height: 1rem; width: 1rem; text-decoration: none; /* unfitted */ color: var(--sklearn-color-unfitted-level-1); border: var(--sklearn-color-unfitted-level-1) 1pt solid; } #sk-container-id-31 a.estimator_doc_link.fitted { /* fitted */ border: var(--sklearn-color-fitted-level-1) 1pt solid; color: var(--sklearn-color-fitted-level-1); } /* On hover */ #sk-container-id-31 a.estimator_doc_link:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } #sk-container-id-31 a.estimator_doc_link.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-3); } </style><div id="sk-container-id-31" class="sk-top-container"><div class="sk-text-repr-fallback"><pre>Pipeline(steps=[('columntransformer', ColumnTransformer(remainder='passthrough', transformers=[('onehotencoder', OneHotEncoder(drop='if_binary'), ['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH'])], verbose_feature_names_out=False)), ('transformedtargetregressor', TransformedTargetRegressor(func=<ufunc 'log10'>, inverse_func=<ufunc 'exp10'>, regressor=Ridge(alpha=1e-10)))])</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class="sk-container" hidden><div class="sk-item sk-dashed-wrapped"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-114" type="checkbox" ><label for="sk-estimator-id-114" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> Pipeline<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.pipeline.Pipeline.html">?<span>Documentation for Pipeline</span></a><span class="sk-estimator-doc-link fitted">i<span>Fitted</span></span></label><div class="sk-toggleable__content fitted"><pre>Pipeline(steps=[('columntransformer', ColumnTransformer(remainder='passthrough', transformers=[('onehotencoder', OneHotEncoder(drop='if_binary'), ['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH'])], verbose_feature_names_out=False)), ('transformedtargetregressor', TransformedTargetRegressor(func=<ufunc 'log10'>, inverse_func=<ufunc 'exp10'>, regressor=Ridge(alpha=1e-10)))])</pre></div> </div></div><div class="sk-serial"><div class="sk-item sk-dashed-wrapped"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-115" type="checkbox" ><label for="sk-estimator-id-115" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> columntransformer: ColumnTransformer<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.compose.ColumnTransformer.html">?<span>Documentation for columntransformer: ColumnTransformer</span></a></label><div class="sk-toggleable__content fitted"><pre>ColumnTransformer(remainder='passthrough', transformers=[('onehotencoder', OneHotEncoder(drop='if_binary'), ['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH'])], verbose_feature_names_out=False)</pre></div> </div></div><div class="sk-parallel"><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-116" type="checkbox" ><label for="sk-estimator-id-116" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted">onehotencoder</label><div class="sk-toggleable__content fitted"><pre>['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH']</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-117" type="checkbox" ><label for="sk-estimator-id-117" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> OneHotEncoder<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.preprocessing.OneHotEncoder.html">?<span>Documentation for OneHotEncoder</span></a></label><div class="sk-toggleable__content fitted"><pre>OneHotEncoder(drop='if_binary')</pre></div> </div></div></div></div></div><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-118" type="checkbox" ><label for="sk-estimator-id-118" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted">remainder</label><div class="sk-toggleable__content fitted"><pre>['EDUCATION', 'EXPERIENCE', 'AGE']</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-119" type="checkbox" ><label for="sk-estimator-id-119" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted">passthrough</label><div class="sk-toggleable__content fitted"><pre>passthrough</pre></div> </div></div></div></div></div></div></div><div class="sk-item sk-dashed-wrapped"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-120" type="checkbox" ><label for="sk-estimator-id-120" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> transformedtargetregressor: TransformedTargetRegressor<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.compose.TransformedTargetRegressor.html">?<span>Documentation for transformedtargetregressor: TransformedTargetRegressor</span></a></label><div class="sk-toggleable__content fitted"><pre>TransformedTargetRegressor(func=<ufunc 'log10'>, inverse_func=<ufunc 'exp10'>, regressor=Ridge(alpha=1e-10))</pre></div> </div></div><div class="sk-parallel"><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-121" type="checkbox" ><label for="sk-estimator-id-121" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted">regressor: Ridge</label><div class="sk-toggleable__content fitted"><pre>Ridge(alpha=1e-10)</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-122" type="checkbox" ><label for="sk-estimator-id-122" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> Ridge<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.linear_model.Ridge.html">?<span>Documentation for Ridge</span></a></label><div class="sk-toggleable__content fitted"><pre>Ridge(alpha=1e-10)</pre></div> </div></div></div></div></div></div></div></div></div></div></div> </div> <br /> <br /> .. GENERATED FROM PYTHON SOURCE LINES 176-179 Then we check the performance of the computed model plotting its predictions on the test set and computing, for example, the median absolute error of the model. .. GENERATED FROM PYTHON SOURCE LINES 179-190 .. code-block:: Python from sklearn.metrics import PredictionErrorDisplay, median_absolute_error mae_train = median_absolute_error(y_train, model.predict(X_train)) y_pred = model.predict(X_test) mae_test = median_absolute_error(y_test, y_pred) scores = { "MedAE on training set": f"{mae_train:.2f} $/hour", "MedAE on testing set": f"{mae_test:.2f} $/hour", } .. GENERATED FROM PYTHON SOURCE LINES 191-201 .. code-block:: Python _, ax = plt.subplots(figsize=(5, 5)) display = PredictionErrorDisplay.from_predictions( y_test, y_pred, kind="actual_vs_predicted", ax=ax, scatter_kwargs={"alpha": 0.5} ) ax.set_title("Ridge model, small regularization") for name, score in scores.items(): ax.plot([], [], " ", label=f"{name}: {score}") ax.legend(loc="upper left") plt.tight_layout() .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_002.png :alt: Ridge model, small regularization :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 202-216 The model learnt is far from being a good model making accurate predictions: this is obvious when looking at the plot above, where good predictions should lie on the black dashed line. In the following section, we will interpret the coefficients of the model. While we do so, we should keep in mind that any conclusion we draw is about the model that we build, rather than about the true (real-world) generative process of the data. Interpreting coefficients: scale matters ---------------------------------------- First of all, we can take a look to the values of the coefficients of the regressor we have fitted. .. GENERATED FROM PYTHON SOURCE LINES 216-226 .. code-block:: Python feature_names = model[:-1].get_feature_names_out() coefs = pd.DataFrame( model[-1].regressor_.coef_, columns=["Coefficients"], index=feature_names, ) coefs .. raw:: html <div class="output_subarea output_html rendered_html output_result"> <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>Coefficients</th> </tr> </thead> <tbody> <tr> <th>RACE_Hispanic</th> <td>-0.013519</td> </tr> <tr> <th>RACE_Other</th> <td>-0.009075</td> </tr> <tr> <th>RACE_White</th> <td>0.022594</td> </tr> <tr> <th>OCCUPATION_Clerical</th> <td>0.000045</td> </tr> <tr> <th>OCCUPATION_Management</th> <td>0.090528</td> </tr> <tr> <th>OCCUPATION_Other</th> <td>-0.025102</td> </tr> <tr> <th>OCCUPATION_Professional</th> <td>0.071964</td> </tr> <tr> <th>OCCUPATION_Sales</th> <td>-0.046636</td> </tr> <tr> <th>OCCUPATION_Service</th> <td>-0.091053</td> </tr> <tr> <th>SECTOR_Construction</th> <td>-0.000198</td> </tr> <tr> <th>SECTOR_Manufacturing</th> <td>0.031255</td> </tr> <tr> <th>SECTOR_Other</th> <td>-0.031025</td> </tr> <tr> <th>MARR_Unmarried</th> <td>-0.032405</td> </tr> <tr> <th>UNION_not_member</th> <td>-0.117154</td> </tr> <tr> <th>SEX_male</th> <td>0.090808</td> </tr> <tr> <th>SOUTH_yes</th> <td>-0.033823</td> </tr> <tr> <th>EDUCATION</th> <td>0.054699</td> </tr> <tr> <th>EXPERIENCE</th> <td>0.035005</td> </tr> <tr> <th>AGE</th> <td>-0.030867</td> </tr> </tbody> </table> </div> </div> <br /> <br /> .. GENERATED FROM PYTHON SOURCE LINES 227-239 The AGE coefficient is expressed in "dollars/hour per living years" while the EDUCATION one is expressed in "dollars/hour per years of education". This representation of the coefficients has the benefit of making clear the practical predictions of the model: an increase of :math:`1` year in AGE means a decrease of :math:`0.030867` dollars/hour, while an increase of :math:`1` year in EDUCATION means an increase of :math:`0.054699` dollars/hour. On the other hand, categorical variables (as UNION or SEX) are adimensional numbers taking either the value 0 or 1. Their coefficients are expressed in dollars/hour. Then, we cannot compare the magnitude of different coefficients since the features have different natural scales, and hence value ranges, because of their different unit of measure. This is more visible if we plot the coefficients. .. GENERATED FROM PYTHON SOURCE LINES 239-246 .. code-block:: Python coefs.plot.barh(figsize=(9, 7)) plt.title("Ridge model, small regularization") plt.axvline(x=0, color=".5") plt.xlabel("Raw coefficient values") plt.subplots_adjust(left=0.3) .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_003.png :alt: Ridge model, small regularization :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_003.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 247-258 Indeed, from the plot above the most important factor in determining WAGE appears to be the variable UNION, even if our intuition might tell us that variables like EXPERIENCE should have more impact. Looking at the coefficient plot to gauge feature importance can be misleading as some of them vary on a small scale, while others, like AGE, varies a lot more, several decades. This is visible if we compare the standard deviations of different features. .. GENERATED FROM PYTHON SOURCE LINES 258-268 .. code-block:: Python X_train_preprocessed = pd.DataFrame( model[:-1].transform(X_train), columns=feature_names ) X_train_preprocessed.std(axis=0).plot.barh(figsize=(9, 7)) plt.title("Feature ranges") plt.xlabel("Std. dev. of feature values") plt.subplots_adjust(left=0.3) .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_004.png :alt: Feature ranges :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_004.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 269-279 Multiplying the coefficients by the standard deviation of the related feature would reduce all the coefficients to the same unit of measure. As we will see :ref:`after<scaling_num>` this is equivalent to normalize numerical variables to their standard deviation, as :math:`y = \sum{coef_i \times X_i} = \sum{(coef_i \times std_i) \times (X_i / std_i)}`. In that way, we emphasize that the greater the variance of a feature, the larger the weight of the corresponding coefficient on the output, all else being equal. .. GENERATED FROM PYTHON SOURCE LINES 279-291 .. code-block:: Python coefs = pd.DataFrame( model[-1].regressor_.coef_ * X_train_preprocessed.std(axis=0), columns=["Coefficient importance"], index=feature_names, ) coefs.plot(kind="barh", figsize=(9, 7)) plt.xlabel("Coefficient values corrected by the feature's std. dev.") plt.title("Ridge model, small regularization") plt.axvline(x=0, color=".5") plt.subplots_adjust(left=0.3) .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_005.png :alt: Ridge model, small regularization :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_005.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 292-319 Now that the coefficients have been scaled, we can safely compare them. .. warning:: Why does the plot above suggest that an increase in age leads to a decrease in wage? Why the :ref:`initial pairplot <marginal_dependencies>` is telling the opposite? The plot above tells us about dependencies between a specific feature and the target when all other features remain constant, i.e., **conditional dependencies**. An increase of the AGE will induce a decrease of the WAGE when all other features remain constant. On the contrary, an increase of the EXPERIENCE will induce an increase of the WAGE when all other features remain constant. Also, AGE, EXPERIENCE and EDUCATION are the three variables that most influence the model. Checking the variability of the coefficients -------------------------------------------- We can check the coefficient variability through cross-validation: it is a form of data perturbation (related to `resampling <https://en.wikipedia.org/wiki/Resampling_(statistics)>`_). If coefficients vary significantly when changing the input dataset their robustness is not guaranteed, and they should probably be interpreted with caution. .. GENERATED FROM PYTHON SOURCE LINES 319-340 .. code-block:: Python from sklearn.model_selection import RepeatedKFold, cross_validate cv = RepeatedKFold(n_splits=5, n_repeats=5, random_state=0) cv_model = cross_validate( model, X, y, cv=cv, return_estimator=True, n_jobs=2, ) coefs = pd.DataFrame( [ est[-1].regressor_.coef_ * est[:-1].transform(X.iloc[train_idx]).std(axis=0) for est, (train_idx, _) in zip(cv_model["estimator"], cv.split(X, y)) ], columns=feature_names, ) .. GENERATED FROM PYTHON SOURCE LINES 341-350 .. code-block:: Python plt.figure(figsize=(9, 7)) sns.stripplot(data=coefs, orient="h", palette="dark:k", alpha=0.5) sns.boxplot(data=coefs, orient="h", color="cyan", saturation=0.5, whis=10) plt.axvline(x=0, color=".5") plt.xlabel("Coefficient importance") plt.title("Coefficient importance and its variability") plt.suptitle("Ridge model, small regularization") plt.subplots_adjust(left=0.3) .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_006.png :alt: Ridge model, small regularization, Coefficient importance and its variability :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_006.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 351-363 The problem of correlated variables ----------------------------------- The AGE and EXPERIENCE coefficients are affected by strong variability which might be due to the collinearity between the 2 features: as AGE and EXPERIENCE vary together in the data, their effect is difficult to tease apart. To verify this interpretation we plot the variability of the AGE and EXPERIENCE coefficient. .. _covariation: .. GENERATED FROM PYTHON SOURCE LINES 363-372 .. code-block:: Python plt.ylabel("Age coefficient") plt.xlabel("Experience coefficient") plt.grid(True) plt.xlim(-0.4, 0.5) plt.ylim(-0.4, 0.5) plt.scatter(coefs["AGE"], coefs["EXPERIENCE"]) _ = plt.title("Co-variations of coefficients for AGE and EXPERIENCE across folds") .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_007.png :alt: Co-variations of coefficients for AGE and EXPERIENCE across folds :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_007.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 373-378 Two regions are populated: when the EXPERIENCE coefficient is positive the AGE one is negative and vice-versa. To go further we remove one of the 2 features and check what is the impact on the model stability. .. GENERATED FROM PYTHON SOURCE LINES 378-399 .. code-block:: Python column_to_drop = ["AGE"] cv_model = cross_validate( model, X.drop(columns=column_to_drop), y, cv=cv, return_estimator=True, n_jobs=2, ) coefs = pd.DataFrame( [ est[-1].regressor_.coef_ * est[:-1].transform(X.drop(columns=column_to_drop).iloc[train_idx]).std(axis=0) for est, (train_idx, _) in zip(cv_model["estimator"], cv.split(X, y)) ], columns=feature_names[:-1], ) .. GENERATED FROM PYTHON SOURCE LINES 400-409 .. code-block:: Python plt.figure(figsize=(9, 7)) sns.stripplot(data=coefs, orient="h", palette="dark:k", alpha=0.5) sns.boxplot(data=coefs, orient="h", color="cyan", saturation=0.5) plt.axvline(x=0, color=".5") plt.title("Coefficient importance and its variability") plt.xlabel("Coefficient importance") plt.suptitle("Ridge model, small regularization, AGE dropped") plt.subplots_adjust(left=0.3) .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_008.png :alt: Ridge model, small regularization, AGE dropped, Coefficient importance and its variability :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_008.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 410-425 The estimation of the EXPERIENCE coefficient now shows a much reduced variability. EXPERIENCE remains important for all models trained during cross-validation. .. _scaling_num: Preprocessing numerical variables --------------------------------- As said above (see ":ref:`the-pipeline`"), we could also choose to scale numerical values before training the model. This can be useful when we apply a similar amount of regularization to all of them in the ridge. The preprocessor is redefined in order to subtract the mean and scale variables to unit variance. .. GENERATED FROM PYTHON SOURCE LINES 425-433 .. code-block:: Python from sklearn.preprocessing import StandardScaler preprocessor = make_column_transformer( (OneHotEncoder(drop="if_binary"), categorical_columns), (StandardScaler(), numerical_columns), ) .. GENERATED FROM PYTHON SOURCE LINES 434-435 The model will stay unchanged. .. GENERATED FROM PYTHON SOURCE LINES 435-444 .. code-block:: Python model = make_pipeline( preprocessor, TransformedTargetRegressor( regressor=Ridge(alpha=1e-10), func=np.log10, inverse_func=sp.special.exp10 ), ) model.fit(X_train, y_train) .. raw:: html <div class="output_subarea output_html rendered_html output_result"> <style>#sk-container-id-32 { /* Definition of color scheme common for light and dark mode */ --sklearn-color-text: black; --sklearn-color-line: gray; /* Definition of color scheme for unfitted estimators */ --sklearn-color-unfitted-level-0: #fff5e6; --sklearn-color-unfitted-level-1: #f6e4d2; --sklearn-color-unfitted-level-2: #ffe0b3; --sklearn-color-unfitted-level-3: chocolate; /* Definition of color scheme for fitted estimators */ --sklearn-color-fitted-level-0: #f0f8ff; --sklearn-color-fitted-level-1: #d4ebff; --sklearn-color-fitted-level-2: #b3dbfd; --sklearn-color-fitted-level-3: cornflowerblue; /* Specific color for light theme */ --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black))); --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white))); --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black))); --sklearn-color-icon: #696969; @media (prefers-color-scheme: dark) { /* Redefinition of color scheme for dark theme */ --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white))); --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111))); --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white))); --sklearn-color-icon: #878787; } } #sk-container-id-32 { color: var(--sklearn-color-text); } #sk-container-id-32 pre { padding: 0; } #sk-container-id-32 input.sk-hidden--visually { border: 0; clip: rect(1px 1px 1px 1px); clip: rect(1px, 1px, 1px, 1px); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } #sk-container-id-32 div.sk-dashed-wrapped { border: 1px dashed var(--sklearn-color-line); margin: 0 0.4em 0.5em 0.4em; box-sizing: border-box; padding-bottom: 0.4em; background-color: var(--sklearn-color-background); } #sk-container-id-32 div.sk-container { /* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */ display: inline-block !important; position: relative; } #sk-container-id-32 div.sk-text-repr-fallback { display: none; } div.sk-parallel-item, div.sk-serial, div.sk-item { /* draw centered vertical line to link estimators */ background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background)); background-size: 2px 100%; background-repeat: no-repeat; background-position: center center; } /* Parallel-specific style estimator block */ #sk-container-id-32 div.sk-parallel-item::after { content: ""; width: 100%; border-bottom: 2px solid var(--sklearn-color-text-on-default-background); flex-grow: 1; } #sk-container-id-32 div.sk-parallel { display: flex; align-items: stretch; justify-content: center; background-color: var(--sklearn-color-background); position: relative; } #sk-container-id-32 div.sk-parallel-item { display: flex; flex-direction: column; } #sk-container-id-32 div.sk-parallel-item:first-child::after { align-self: flex-end; width: 50%; } #sk-container-id-32 div.sk-parallel-item:last-child::after { align-self: flex-start; width: 50%; } #sk-container-id-32 div.sk-parallel-item:only-child::after { width: 0; } /* Serial-specific style estimator block */ #sk-container-id-32 div.sk-serial { display: flex; flex-direction: column; align-items: center; background-color: var(--sklearn-color-background); padding-right: 1em; padding-left: 1em; } /* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is clickable and can be expanded/collapsed. - Pipeline and ColumnTransformer use this feature and define the default style - Estimators will overwrite some part of the style using the `sk-estimator` class */ /* Pipeline and ColumnTransformer style (default) */ #sk-container-id-32 div.sk-toggleable { /* Default theme specific background. It is overwritten whether we have a specific estimator or a Pipeline/ColumnTransformer */ background-color: var(--sklearn-color-background); } /* Toggleable label */ #sk-container-id-32 label.sk-toggleable__label { cursor: pointer; display: block; width: 100%; margin-bottom: 0; padding: 0.5em; box-sizing: border-box; text-align: center; } #sk-container-id-32 label.sk-toggleable__label-arrow:before { /* Arrow on the left of the label */ content: "▸"; float: left; margin-right: 0.25em; color: var(--sklearn-color-icon); } #sk-container-id-32 label.sk-toggleable__label-arrow:hover:before { color: var(--sklearn-color-text); } /* Toggleable content - dropdown */ #sk-container-id-32 div.sk-toggleable__content { max-height: 0; max-width: 0; overflow: hidden; text-align: left; /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-32 div.sk-toggleable__content.fitted { /* fitted */ background-color: var(--sklearn-color-fitted-level-0); } #sk-container-id-32 div.sk-toggleable__content pre { margin: 0.2em; border-radius: 0.25em; color: var(--sklearn-color-text); /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-32 div.sk-toggleable__content.fitted pre { /* unfitted */ background-color: var(--sklearn-color-fitted-level-0); } #sk-container-id-32 input.sk-toggleable__control:checked~div.sk-toggleable__content { /* Expand drop-down */ max-height: 200px; max-width: 100%; overflow: auto; } #sk-container-id-32 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before { content: "▾"; } /* Pipeline/ColumnTransformer-specific style */ #sk-container-id-32 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label { color: var(--sklearn-color-text); background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-32 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label { background-color: var(--sklearn-color-fitted-level-2); } /* Estimator-specific style */ /* Colorize estimator box */ #sk-container-id-32 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-32 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label { /* fitted */ background-color: var(--sklearn-color-fitted-level-2); } #sk-container-id-32 div.sk-label label.sk-toggleable__label, #sk-container-id-32 div.sk-label label { /* The background is the default theme color */ color: var(--sklearn-color-text-on-default-background); } /* On hover, darken the color of the background */ #sk-container-id-32 div.sk-label:hover label.sk-toggleable__label { color: var(--sklearn-color-text); background-color: var(--sklearn-color-unfitted-level-2); } /* Label box, darken color on hover, fitted */ #sk-container-id-32 div.sk-label.fitted:hover label.sk-toggleable__label.fitted { color: var(--sklearn-color-text); background-color: var(--sklearn-color-fitted-level-2); } /* Estimator label */ #sk-container-id-32 div.sk-label label { font-family: monospace; font-weight: bold; display: inline-block; line-height: 1.2em; } #sk-container-id-32 div.sk-label-container { text-align: center; } /* Estimator-specific */ #sk-container-id-32 div.sk-estimator { font-family: monospace; border: 1px dotted var(--sklearn-color-border-box); border-radius: 0.25em; box-sizing: border-box; margin-bottom: 0.5em; /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-32 div.sk-estimator.fitted { /* fitted */ background-color: var(--sklearn-color-fitted-level-0); } /* on hover */ #sk-container-id-32 div.sk-estimator:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-32 div.sk-estimator.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-2); } /* Specification for estimator info (e.g. "i" and "?") */ /* Common style for "i" and "?" */ .sk-estimator-doc-link, a:link.sk-estimator-doc-link, a:visited.sk-estimator-doc-link { float: right; font-size: smaller; line-height: 1em; font-family: monospace; background-color: var(--sklearn-color-background); border-radius: 1em; height: 1em; width: 1em; text-decoration: none !important; margin-left: 1ex; /* unfitted */ border: var(--sklearn-color-unfitted-level-1) 1pt solid; color: var(--sklearn-color-unfitted-level-1); } .sk-estimator-doc-link.fitted, a:link.sk-estimator-doc-link.fitted, a:visited.sk-estimator-doc-link.fitted { /* fitted */ border: var(--sklearn-color-fitted-level-1) 1pt solid; color: var(--sklearn-color-fitted-level-1); } /* On hover */ div.sk-estimator:hover .sk-estimator-doc-link:hover, .sk-estimator-doc-link:hover, div.sk-label-container:hover .sk-estimator-doc-link:hover, .sk-estimator-doc-link:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover, .sk-estimator-doc-link.fitted:hover, div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover, .sk-estimator-doc-link.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } /* Span, style for the box shown on hovering the info icon */ .sk-estimator-doc-link span { display: none; z-index: 9999; position: relative; font-weight: normal; right: .2ex; padding: .5ex; margin: .5ex; width: min-content; min-width: 20ex; max-width: 50ex; color: var(--sklearn-color-text); box-shadow: 2pt 2pt 4pt #999; /* unfitted */ background: var(--sklearn-color-unfitted-level-0); border: .5pt solid var(--sklearn-color-unfitted-level-3); } .sk-estimator-doc-link.fitted span { /* fitted */ background: var(--sklearn-color-fitted-level-0); border: var(--sklearn-color-fitted-level-3); } .sk-estimator-doc-link:hover span { display: block; } /* "?"-specific style due to the `<a>` HTML tag */ #sk-container-id-32 a.estimator_doc_link { float: right; font-size: 1rem; line-height: 1em; font-family: monospace; background-color: var(--sklearn-color-background); border-radius: 1rem; height: 1rem; width: 1rem; text-decoration: none; /* unfitted */ color: var(--sklearn-color-unfitted-level-1); border: var(--sklearn-color-unfitted-level-1) 1pt solid; } #sk-container-id-32 a.estimator_doc_link.fitted { /* fitted */ border: var(--sklearn-color-fitted-level-1) 1pt solid; color: var(--sklearn-color-fitted-level-1); } /* On hover */ #sk-container-id-32 a.estimator_doc_link:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } #sk-container-id-32 a.estimator_doc_link.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-3); } </style><div id="sk-container-id-32" class="sk-top-container"><div class="sk-text-repr-fallback"><pre>Pipeline(steps=[('columntransformer', ColumnTransformer(transformers=[('onehotencoder', OneHotEncoder(drop='if_binary'), ['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH']), ('standardscaler', StandardScaler(), ['EDUCATION', 'EXPERIENCE', 'AGE'])])), ('transformedtargetregressor', TransformedTargetRegressor(func=<ufunc 'log10'>, inverse_func=<ufunc 'exp10'>, regressor=Ridge(alpha=1e-10)))])</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class="sk-container" hidden><div class="sk-item sk-dashed-wrapped"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-123" type="checkbox" ><label for="sk-estimator-id-123" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> Pipeline<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.pipeline.Pipeline.html">?<span>Documentation for Pipeline</span></a><span class="sk-estimator-doc-link fitted">i<span>Fitted</span></span></label><div class="sk-toggleable__content fitted"><pre>Pipeline(steps=[('columntransformer', ColumnTransformer(transformers=[('onehotencoder', OneHotEncoder(drop='if_binary'), ['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH']), ('standardscaler', StandardScaler(), ['EDUCATION', 'EXPERIENCE', 'AGE'])])), ('transformedtargetregressor', TransformedTargetRegressor(func=<ufunc 'log10'>, inverse_func=<ufunc 'exp10'>, regressor=Ridge(alpha=1e-10)))])</pre></div> </div></div><div class="sk-serial"><div class="sk-item sk-dashed-wrapped"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-124" type="checkbox" ><label for="sk-estimator-id-124" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> columntransformer: ColumnTransformer<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.compose.ColumnTransformer.html">?<span>Documentation for columntransformer: ColumnTransformer</span></a></label><div class="sk-toggleable__content fitted"><pre>ColumnTransformer(transformers=[('onehotencoder', OneHotEncoder(drop='if_binary'), ['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH']), ('standardscaler', StandardScaler(), ['EDUCATION', 'EXPERIENCE', 'AGE'])])</pre></div> </div></div><div class="sk-parallel"><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-125" type="checkbox" ><label for="sk-estimator-id-125" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted">onehotencoder</label><div class="sk-toggleable__content fitted"><pre>['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH']</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-126" type="checkbox" ><label for="sk-estimator-id-126" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> OneHotEncoder<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.preprocessing.OneHotEncoder.html">?<span>Documentation for OneHotEncoder</span></a></label><div class="sk-toggleable__content fitted"><pre>OneHotEncoder(drop='if_binary')</pre></div> </div></div></div></div></div><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-127" type="checkbox" ><label for="sk-estimator-id-127" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted">standardscaler</label><div class="sk-toggleable__content fitted"><pre>['EDUCATION', 'EXPERIENCE', 'AGE']</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-128" type="checkbox" ><label for="sk-estimator-id-128" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> StandardScaler<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.preprocessing.StandardScaler.html">?<span>Documentation for StandardScaler</span></a></label><div class="sk-toggleable__content fitted"><pre>StandardScaler()</pre></div> </div></div></div></div></div></div></div><div class="sk-item sk-dashed-wrapped"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-129" type="checkbox" ><label for="sk-estimator-id-129" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> transformedtargetregressor: TransformedTargetRegressor<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.compose.TransformedTargetRegressor.html">?<span>Documentation for transformedtargetregressor: TransformedTargetRegressor</span></a></label><div class="sk-toggleable__content fitted"><pre>TransformedTargetRegressor(func=<ufunc 'log10'>, inverse_func=<ufunc 'exp10'>, regressor=Ridge(alpha=1e-10))</pre></div> </div></div><div class="sk-parallel"><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-130" type="checkbox" ><label for="sk-estimator-id-130" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted">regressor: Ridge</label><div class="sk-toggleable__content fitted"><pre>Ridge(alpha=1e-10)</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-131" type="checkbox" ><label for="sk-estimator-id-131" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> Ridge<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.linear_model.Ridge.html">?<span>Documentation for Ridge</span></a></label><div class="sk-toggleable__content fitted"><pre>Ridge(alpha=1e-10)</pre></div> </div></div></div></div></div></div></div></div></div></div></div> </div> <br /> <br /> .. GENERATED FROM PYTHON SOURCE LINES 445-448 Again, we check the performance of the computed model using, for example, the median absolute error of the model and the R squared coefficient. .. GENERATED FROM PYTHON SOURCE LINES 448-467 .. code-block:: Python mae_train = median_absolute_error(y_train, model.predict(X_train)) y_pred = model.predict(X_test) mae_test = median_absolute_error(y_test, y_pred) scores = { "MedAE on training set": f"{mae_train:.2f} $/hour", "MedAE on testing set": f"{mae_test:.2f} $/hour", } _, ax = plt.subplots(figsize=(5, 5)) display = PredictionErrorDisplay.from_predictions( y_test, y_pred, kind="actual_vs_predicted", ax=ax, scatter_kwargs={"alpha": 0.5} ) ax.set_title("Ridge model, small regularization") for name, score in scores.items(): ax.plot([], [], " ", label=f"{name}: {score}") ax.legend(loc="upper left") plt.tight_layout() .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_009.png :alt: Ridge model, small regularization :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_009.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 468-470 For the coefficient analysis, scaling is not needed this time because it was performed during the preprocessing step. .. GENERATED FROM PYTHON SOURCE LINES 470-482 .. code-block:: Python coefs = pd.DataFrame( model[-1].regressor_.coef_, columns=["Coefficients importance"], index=feature_names, ) coefs.plot.barh(figsize=(9, 7)) plt.title("Ridge model, small regularization, normalized variables") plt.xlabel("Raw coefficient values") plt.axvline(x=0, color=".5") plt.subplots_adjust(left=0.3) .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_010.png :alt: Ridge model, small regularization, normalized variables :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_010.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 483-487 We now inspect the coefficients across several cross-validation folds. As in the above example, we do not need to scale the coefficients by the std. dev. of the feature values since this scaling was already done in the preprocessing step of the pipeline. .. GENERATED FROM PYTHON SOURCE LINES 487-500 .. code-block:: Python cv_model = cross_validate( model, X, y, cv=cv, return_estimator=True, n_jobs=2, ) coefs = pd.DataFrame( [est[-1].regressor_.coef_ for est in cv_model["estimator"]], columns=feature_names ) .. GENERATED FROM PYTHON SOURCE LINES 501-508 .. code-block:: Python plt.figure(figsize=(9, 7)) sns.stripplot(data=coefs, orient="h", palette="dark:k", alpha=0.5) sns.boxplot(data=coefs, orient="h", color="cyan", saturation=0.5, whis=10) plt.axvline(x=0, color=".5") plt.title("Coefficient variability") plt.subplots_adjust(left=0.3) .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_011.png :alt: Coefficient variability :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_011.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 509-522 The result is quite similar to the non-normalized case. Linear models with regularization --------------------------------- In machine-learning practice, ridge regression is more often used with non-negligible regularization. Above, we limited this regularization to a very little amount. Regularization improves the conditioning of the problem and reduces the variance of the estimates. :class:`~sklearn.linear_model.RidgeCV` applies cross validation in order to determine which value of the regularization parameter (`alpha`) is best suited for prediction. .. GENERATED FROM PYTHON SOURCE LINES 522-536 .. code-block:: Python from sklearn.linear_model import RidgeCV alphas = np.logspace(-10, 10, 21) # alpha values to be chosen from by cross-validation model = make_pipeline( preprocessor, TransformedTargetRegressor( regressor=RidgeCV(alphas=alphas), func=np.log10, inverse_func=sp.special.exp10, ), ) model.fit(X_train, y_train) .. raw:: html <div class="output_subarea output_html rendered_html output_result"> <style>#sk-container-id-33 { /* Definition of color scheme common for light and dark mode */ --sklearn-color-text: black; --sklearn-color-line: gray; /* Definition of color scheme for unfitted estimators */ --sklearn-color-unfitted-level-0: #fff5e6; --sklearn-color-unfitted-level-1: #f6e4d2; --sklearn-color-unfitted-level-2: #ffe0b3; --sklearn-color-unfitted-level-3: chocolate; /* Definition of color scheme for fitted estimators */ --sklearn-color-fitted-level-0: #f0f8ff; --sklearn-color-fitted-level-1: #d4ebff; --sklearn-color-fitted-level-2: #b3dbfd; --sklearn-color-fitted-level-3: cornflowerblue; /* Specific color for light theme */ --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black))); --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white))); --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black))); --sklearn-color-icon: #696969; @media (prefers-color-scheme: dark) { /* Redefinition of color scheme for dark theme */ --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white))); --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111))); --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white))); --sklearn-color-icon: #878787; } } #sk-container-id-33 { color: var(--sklearn-color-text); } #sk-container-id-33 pre { padding: 0; } #sk-container-id-33 input.sk-hidden--visually { border: 0; clip: rect(1px 1px 1px 1px); clip: rect(1px, 1px, 1px, 1px); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } #sk-container-id-33 div.sk-dashed-wrapped { border: 1px dashed var(--sklearn-color-line); margin: 0 0.4em 0.5em 0.4em; box-sizing: border-box; padding-bottom: 0.4em; background-color: var(--sklearn-color-background); } #sk-container-id-33 div.sk-container { /* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */ display: inline-block !important; position: relative; } #sk-container-id-33 div.sk-text-repr-fallback { display: none; } div.sk-parallel-item, div.sk-serial, div.sk-item { /* draw centered vertical line to link estimators */ background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background)); background-size: 2px 100%; background-repeat: no-repeat; background-position: center center; } /* Parallel-specific style estimator block */ #sk-container-id-33 div.sk-parallel-item::after { content: ""; width: 100%; border-bottom: 2px solid var(--sklearn-color-text-on-default-background); flex-grow: 1; } #sk-container-id-33 div.sk-parallel { display: flex; align-items: stretch; justify-content: center; background-color: var(--sklearn-color-background); position: relative; } #sk-container-id-33 div.sk-parallel-item { display: flex; flex-direction: column; } #sk-container-id-33 div.sk-parallel-item:first-child::after { align-self: flex-end; width: 50%; } #sk-container-id-33 div.sk-parallel-item:last-child::after { align-self: flex-start; width: 50%; } #sk-container-id-33 div.sk-parallel-item:only-child::after { width: 0; } /* Serial-specific style estimator block */ #sk-container-id-33 div.sk-serial { display: flex; flex-direction: column; align-items: center; background-color: var(--sklearn-color-background); padding-right: 1em; padding-left: 1em; } /* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is clickable and can be expanded/collapsed. - Pipeline and ColumnTransformer use this feature and define the default style - Estimators will overwrite some part of the style using the `sk-estimator` class */ /* Pipeline and ColumnTransformer style (default) */ #sk-container-id-33 div.sk-toggleable { /* Default theme specific background. It is overwritten whether we have a specific estimator or a Pipeline/ColumnTransformer */ background-color: var(--sklearn-color-background); } /* Toggleable label */ #sk-container-id-33 label.sk-toggleable__label { cursor: pointer; display: block; width: 100%; margin-bottom: 0; padding: 0.5em; box-sizing: border-box; text-align: center; } #sk-container-id-33 label.sk-toggleable__label-arrow:before { /* Arrow on the left of the label */ content: "▸"; float: left; margin-right: 0.25em; color: var(--sklearn-color-icon); } #sk-container-id-33 label.sk-toggleable__label-arrow:hover:before { color: var(--sklearn-color-text); } /* Toggleable content - dropdown */ #sk-container-id-33 div.sk-toggleable__content { max-height: 0; max-width: 0; overflow: hidden; text-align: left; /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-33 div.sk-toggleable__content.fitted { /* fitted */ background-color: var(--sklearn-color-fitted-level-0); } #sk-container-id-33 div.sk-toggleable__content pre { margin: 0.2em; border-radius: 0.25em; color: var(--sklearn-color-text); /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-33 div.sk-toggleable__content.fitted pre { /* unfitted */ background-color: var(--sklearn-color-fitted-level-0); } #sk-container-id-33 input.sk-toggleable__control:checked~div.sk-toggleable__content { /* Expand drop-down */ max-height: 200px; max-width: 100%; overflow: auto; } #sk-container-id-33 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before { content: "▾"; } /* Pipeline/ColumnTransformer-specific style */ #sk-container-id-33 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label { color: var(--sklearn-color-text); background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-33 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label { background-color: var(--sklearn-color-fitted-level-2); } /* Estimator-specific style */ /* Colorize estimator box */ #sk-container-id-33 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-33 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label { /* fitted */ background-color: var(--sklearn-color-fitted-level-2); } #sk-container-id-33 div.sk-label label.sk-toggleable__label, #sk-container-id-33 div.sk-label label { /* The background is the default theme color */ color: var(--sklearn-color-text-on-default-background); } /* On hover, darken the color of the background */ #sk-container-id-33 div.sk-label:hover label.sk-toggleable__label { color: var(--sklearn-color-text); background-color: var(--sklearn-color-unfitted-level-2); } /* Label box, darken color on hover, fitted */ #sk-container-id-33 div.sk-label.fitted:hover label.sk-toggleable__label.fitted { color: var(--sklearn-color-text); background-color: var(--sklearn-color-fitted-level-2); } /* Estimator label */ #sk-container-id-33 div.sk-label label { font-family: monospace; font-weight: bold; display: inline-block; line-height: 1.2em; } #sk-container-id-33 div.sk-label-container { text-align: center; } /* Estimator-specific */ #sk-container-id-33 div.sk-estimator { font-family: monospace; border: 1px dotted var(--sklearn-color-border-box); border-radius: 0.25em; box-sizing: border-box; margin-bottom: 0.5em; /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-33 div.sk-estimator.fitted { /* fitted */ background-color: var(--sklearn-color-fitted-level-0); } /* on hover */ #sk-container-id-33 div.sk-estimator:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-33 div.sk-estimator.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-2); } /* Specification for estimator info (e.g. "i" and "?") */ /* Common style for "i" and "?" */ .sk-estimator-doc-link, a:link.sk-estimator-doc-link, a:visited.sk-estimator-doc-link { float: right; font-size: smaller; line-height: 1em; font-family: monospace; background-color: var(--sklearn-color-background); border-radius: 1em; height: 1em; width: 1em; text-decoration: none !important; margin-left: 1ex; /* unfitted */ border: var(--sklearn-color-unfitted-level-1) 1pt solid; color: var(--sklearn-color-unfitted-level-1); } .sk-estimator-doc-link.fitted, a:link.sk-estimator-doc-link.fitted, a:visited.sk-estimator-doc-link.fitted { /* fitted */ border: var(--sklearn-color-fitted-level-1) 1pt solid; color: var(--sklearn-color-fitted-level-1); } /* On hover */ div.sk-estimator:hover .sk-estimator-doc-link:hover, .sk-estimator-doc-link:hover, div.sk-label-container:hover .sk-estimator-doc-link:hover, .sk-estimator-doc-link:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover, .sk-estimator-doc-link.fitted:hover, div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover, .sk-estimator-doc-link.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } /* Span, style for the box shown on hovering the info icon */ .sk-estimator-doc-link span { display: none; z-index: 9999; position: relative; font-weight: normal; right: .2ex; padding: .5ex; margin: .5ex; width: min-content; min-width: 20ex; max-width: 50ex; color: var(--sklearn-color-text); box-shadow: 2pt 2pt 4pt #999; /* unfitted */ background: var(--sklearn-color-unfitted-level-0); border: .5pt solid var(--sklearn-color-unfitted-level-3); } .sk-estimator-doc-link.fitted span { /* fitted */ background: var(--sklearn-color-fitted-level-0); border: var(--sklearn-color-fitted-level-3); } .sk-estimator-doc-link:hover span { display: block; } /* "?"-specific style due to the `<a>` HTML tag */ #sk-container-id-33 a.estimator_doc_link { float: right; font-size: 1rem; line-height: 1em; font-family: monospace; background-color: var(--sklearn-color-background); border-radius: 1rem; height: 1rem; width: 1rem; text-decoration: none; /* unfitted */ color: var(--sklearn-color-unfitted-level-1); border: var(--sklearn-color-unfitted-level-1) 1pt solid; } #sk-container-id-33 a.estimator_doc_link.fitted { /* fitted */ border: var(--sklearn-color-fitted-level-1) 1pt solid; color: var(--sklearn-color-fitted-level-1); } /* On hover */ #sk-container-id-33 a.estimator_doc_link:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } #sk-container-id-33 a.estimator_doc_link.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-3); } </style><div id="sk-container-id-33" class="sk-top-container"><div class="sk-text-repr-fallback"><pre>Pipeline(steps=[('columntransformer', ColumnTransformer(transformers=[('onehotencoder', OneHotEncoder(drop='if_binary'), ['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH']), ('standardscaler', StandardScaler(), ['EDUCATION', 'EXPERIENCE', 'AGE'])])), ('transformedtargetregressor', TransformedTargetRegressor(func=<ufunc 'log10'>, inverse_func=<ufunc 'exp10'>, regressor=RidgeCV(alphas=array([1.e-10, 1.e-09, 1.e-08, 1.e-07, 1.e-06, 1.e-05, 1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01, 1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07, 1.e+08, 1.e+09, 1.e+10]))))])</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class="sk-container" hidden><div class="sk-item sk-dashed-wrapped"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-132" type="checkbox" ><label for="sk-estimator-id-132" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> Pipeline<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.pipeline.Pipeline.html">?<span>Documentation for Pipeline</span></a><span class="sk-estimator-doc-link fitted">i<span>Fitted</span></span></label><div class="sk-toggleable__content fitted"><pre>Pipeline(steps=[('columntransformer', ColumnTransformer(transformers=[('onehotencoder', OneHotEncoder(drop='if_binary'), ['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH']), ('standardscaler', StandardScaler(), ['EDUCATION', 'EXPERIENCE', 'AGE'])])), ('transformedtargetregressor', TransformedTargetRegressor(func=<ufunc 'log10'>, inverse_func=<ufunc 'exp10'>, regressor=RidgeCV(alphas=array([1.e-10, 1.e-09, 1.e-08, 1.e-07, 1.e-06, 1.e-05, 1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01, 1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07, 1.e+08, 1.e+09, 1.e+10]))))])</pre></div> </div></div><div class="sk-serial"><div class="sk-item sk-dashed-wrapped"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-133" type="checkbox" ><label for="sk-estimator-id-133" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> columntransformer: ColumnTransformer<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.compose.ColumnTransformer.html">?<span>Documentation for columntransformer: ColumnTransformer</span></a></label><div class="sk-toggleable__content fitted"><pre>ColumnTransformer(transformers=[('onehotencoder', OneHotEncoder(drop='if_binary'), ['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH']), ('standardscaler', StandardScaler(), ['EDUCATION', 'EXPERIENCE', 'AGE'])])</pre></div> </div></div><div class="sk-parallel"><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-134" type="checkbox" ><label for="sk-estimator-id-134" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted">onehotencoder</label><div class="sk-toggleable__content fitted"><pre>['RACE', 'OCCUPATION', 'SECTOR', 'MARR', 'UNION', 'SEX', 'SOUTH']</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-135" type="checkbox" ><label for="sk-estimator-id-135" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> OneHotEncoder<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.preprocessing.OneHotEncoder.html">?<span>Documentation for OneHotEncoder</span></a></label><div class="sk-toggleable__content fitted"><pre>OneHotEncoder(drop='if_binary')</pre></div> </div></div></div></div></div><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-136" type="checkbox" ><label for="sk-estimator-id-136" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted">standardscaler</label><div class="sk-toggleable__content fitted"><pre>['EDUCATION', 'EXPERIENCE', 'AGE']</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-137" type="checkbox" ><label for="sk-estimator-id-137" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> StandardScaler<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.preprocessing.StandardScaler.html">?<span>Documentation for StandardScaler</span></a></label><div class="sk-toggleable__content fitted"><pre>StandardScaler()</pre></div> </div></div></div></div></div></div></div><div class="sk-item sk-dashed-wrapped"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-138" type="checkbox" ><label for="sk-estimator-id-138" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> transformedtargetregressor: TransformedTargetRegressor<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.compose.TransformedTargetRegressor.html">?<span>Documentation for transformedtargetregressor: TransformedTargetRegressor</span></a></label><div class="sk-toggleable__content fitted"><pre>TransformedTargetRegressor(func=<ufunc 'log10'>, inverse_func=<ufunc 'exp10'>, regressor=RidgeCV(alphas=array([1.e-10, 1.e-09, 1.e-08, 1.e-07, 1.e-06, 1.e-05, 1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01, 1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07, 1.e+08, 1.e+09, 1.e+10])))</pre></div> </div></div><div class="sk-parallel"><div class="sk-parallel-item"><div class="sk-item"><div class="sk-label-container"><div class="sk-label fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-139" type="checkbox" ><label for="sk-estimator-id-139" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted">regressor: RidgeCV</label><div class="sk-toggleable__content fitted"><pre>RidgeCV(alphas=array([1.e-10, 1.e-09, 1.e-08, 1.e-07, 1.e-06, 1.e-05, 1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01, 1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07, 1.e+08, 1.e+09, 1.e+10]))</pre></div> </div></div><div class="sk-serial"><div class="sk-item"><div class="sk-estimator fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-140" type="checkbox" ><label for="sk-estimator-id-140" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> RidgeCV<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.linear_model.RidgeCV.html">?<span>Documentation for RidgeCV</span></a></label><div class="sk-toggleable__content fitted"><pre>RidgeCV(alphas=array([1.e-10, 1.e-09, 1.e-08, 1.e-07, 1.e-06, 1.e-05, 1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01, 1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07, 1.e+08, 1.e+09, 1.e+10]))</pre></div> </div></div></div></div></div></div></div></div></div></div></div> </div> <br /> <br /> .. GENERATED FROM PYTHON SOURCE LINES 537-538 First we check which value of :math:`\alpha` has been selected. .. GENERATED FROM PYTHON SOURCE LINES 538-541 .. code-block:: Python model[-1].regressor_.alpha_ .. rst-class:: sphx-glr-script-out .. code-block:: none 10.0 .. GENERATED FROM PYTHON SOURCE LINES 542-543 Then we check the quality of the predictions. .. GENERATED FROM PYTHON SOURCE LINES 543-561 .. code-block:: Python mae_train = median_absolute_error(y_train, model.predict(X_train)) y_pred = model.predict(X_test) mae_test = median_absolute_error(y_test, y_pred) scores = { "MedAE on training set": f"{mae_train:.2f} $/hour", "MedAE on testing set": f"{mae_test:.2f} $/hour", } _, ax = plt.subplots(figsize=(5, 5)) display = PredictionErrorDisplay.from_predictions( y_test, y_pred, kind="actual_vs_predicted", ax=ax, scatter_kwargs={"alpha": 0.5} ) ax.set_title("Ridge model, optimum regularization") for name, score in scores.items(): ax.plot([], [], " ", label=f"{name}: {score}") ax.legend(loc="upper left") plt.tight_layout() .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_012.png :alt: Ridge model, optimum regularization :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_012.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 562-564 The ability to reproduce the data of the regularized model is similar to the one of the non-regularized model. .. GENERATED FROM PYTHON SOURCE LINES 564-576 .. code-block:: Python coefs = pd.DataFrame( model[-1].regressor_.coef_, columns=["Coefficients importance"], index=feature_names, ) coefs.plot.barh(figsize=(9, 7)) plt.title("Ridge model, with regularization, normalized variables") plt.xlabel("Raw coefficient values") plt.axvline(x=0, color=".5") plt.subplots_adjust(left=0.3) .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_013.png :alt: Ridge model, with regularization, normalized variables :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_013.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 577-590 The coefficients are significantly different. AGE and EXPERIENCE coefficients are both positive but they now have less influence on the prediction. The regularization reduces the influence of correlated variables on the model because the weight is shared between the two predictive variables, so neither alone would have strong weights. On the other hand, the weights obtained with regularization are more stable (see the :ref:`ridge_regression` User Guide section). This increased stability is visible from the plot, obtained from data perturbations, in a cross-validation. This plot can be compared with the :ref:`previous one<covariation>`. .. GENERATED FROM PYTHON SOURCE LINES 590-603 .. code-block:: Python cv_model = cross_validate( model, X, y, cv=cv, return_estimator=True, n_jobs=2, ) coefs = pd.DataFrame( [est[-1].regressor_.coef_ for est in cv_model["estimator"]], columns=feature_names ) .. GENERATED FROM PYTHON SOURCE LINES 604-612 .. code-block:: Python plt.ylabel("Age coefficient") plt.xlabel("Experience coefficient") plt.grid(True) plt.xlim(-0.4, 0.5) plt.ylim(-0.4, 0.5) plt.scatter(coefs["AGE"], coefs["EXPERIENCE"]) _ = plt.title("Co-variations of coefficients for AGE and EXPERIENCE across folds") .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_014.png :alt: Co-variations of coefficients for AGE and EXPERIENCE across folds :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_014.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 613-624 Linear models with sparse coefficients -------------------------------------- Another possibility to take into account correlated variables in the dataset, is to estimate sparse coefficients. In some way we already did it manually when we dropped the AGE column in a previous ridge estimation. Lasso models (see the :ref:`lasso` User Guide section) estimates sparse coefficients. :class:`~sklearn.linear_model.LassoCV` applies cross validation in order to determine which value of the regularization parameter (`alpha`) is best suited for the model estimation. .. GENERATED FROM PYTHON SOURCE LINES 624-639 .. code-block:: Python from sklearn.linear_model import LassoCV alphas = np.logspace(-10, 10, 21) # alpha values to be chosen from by cross-validation model = make_pipeline( preprocessor, TransformedTargetRegressor( regressor=LassoCV(alphas=alphas, max_iter=100_000), func=np.log10, inverse_func=sp.special.exp10, ), ) _ = model.fit(X_train, y_train) .. GENERATED FROM PYTHON SOURCE LINES 640-641 First we verify which value of :math:`\alpha` has been selected. .. GENERATED FROM PYTHON SOURCE LINES 641-644 .. code-block:: Python model[-1].regressor_.alpha_ .. rst-class:: sphx-glr-script-out .. code-block:: none 0.001 .. GENERATED FROM PYTHON SOURCE LINES 645-646 Then we check the quality of the predictions. .. GENERATED FROM PYTHON SOURCE LINES 646-665 .. code-block:: Python mae_train = median_absolute_error(y_train, model.predict(X_train)) y_pred = model.predict(X_test) mae_test = median_absolute_error(y_test, y_pred) scores = { "MedAE on training set": f"{mae_train:.2f} $/hour", "MedAE on testing set": f"{mae_test:.2f} $/hour", } _, ax = plt.subplots(figsize=(6, 6)) display = PredictionErrorDisplay.from_predictions( y_test, y_pred, kind="actual_vs_predicted", ax=ax, scatter_kwargs={"alpha": 0.5} ) ax.set_title("Lasso model, optimum regularization") for name, score in scores.items(): ax.plot([], [], " ", label=f"{name}: {score}") ax.legend(loc="upper left") plt.tight_layout() .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_015.png :alt: Lasso model, optimum regularization :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_015.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 666-667 For our dataset, again the model is not very predictive. .. GENERATED FROM PYTHON SOURCE LINES 667-678 .. code-block:: Python coefs = pd.DataFrame( model[-1].regressor_.coef_, columns=["Coefficients importance"], index=feature_names, ) coefs.plot(kind="barh", figsize=(9, 7)) plt.title("Lasso model, optimum regularization, normalized variables") plt.axvline(x=0, color=".5") plt.subplots_adjust(left=0.3) .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_016.png :alt: Lasso model, optimum regularization, normalized variables :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_016.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 679-690 A Lasso model identifies the correlation between AGE and EXPERIENCE and suppresses one of them for the sake of the prediction. It is important to keep in mind that the coefficients that have been dropped may still be related to the outcome by themselves: the model chose to suppress them because they bring little or no additional information on top of the other features. Additionally, this selection is unstable for correlated features, and should be interpreted with caution. Indeed, we can check the variability of the coefficients across folds. .. GENERATED FROM PYTHON SOURCE LINES 690-702 .. code-block:: Python cv_model = cross_validate( model, X, y, cv=cv, return_estimator=True, n_jobs=2, ) coefs = pd.DataFrame( [est[-1].regressor_.coef_ for est in cv_model["estimator"]], columns=feature_names ) .. GENERATED FROM PYTHON SOURCE LINES 703-710 .. code-block:: Python plt.figure(figsize=(9, 7)) sns.stripplot(data=coefs, orient="h", palette="dark:k", alpha=0.5) sns.boxplot(data=coefs, orient="h", color="cyan", saturation=0.5, whis=100) plt.axvline(x=0, color=".5") plt.title("Coefficient variability") plt.subplots_adjust(left=0.3) .. image-sg:: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_017.png :alt: Coefficient variability :srcset: /auto_examples/inspection/images/sphx_glr_plot_linear_model_coefficient_interpretation_017.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 711-758 We observe that the AGE and EXPERIENCE coefficients are varying a lot depending of the fold. Wrong causal interpretation --------------------------- Policy makers might want to know the effect of education on wage to assess whether or not a certain policy designed to entice people to pursue more education would make economic sense. While Machine Learning models are great for measuring statistical associations, they are generally unable to infer causal effects. It might be tempting to look at the coefficient of education on wage from our last model (or any model for that matter) and conclude that it captures the true effect of a change in the standardized education variable on wages. Unfortunately there are likely unobserved confounding variables that either inflate or deflate that coefficient. A confounding variable is a variable that causes both EDUCATION and WAGE. One example of such variable is ability. Presumably, more able people are more likely to pursue education while at the same time being more likely to earn a higher hourly wage at any level of education. In this case, ability induces a positive `Omitted Variable Bias <https://en.wikipedia.org/wiki/Omitted-variable_bias>`_ (OVB) on the EDUCATION coefficient, thereby exaggerating the effect of education on wages. See the :ref:`sphx_glr_auto_examples_inspection_plot_causal_interpretation.py` for a simulated case of ability OVB. Lessons learned --------------- * Coefficients must be scaled to the same unit of measure to retrieve feature importance. Scaling them with the standard-deviation of the feature is a useful proxy. * Coefficients in multivariate linear models represent the dependency between a given feature and the target, **conditional** on the other features. * Correlated features induce instabilities in the coefficients of linear models and their effects cannot be well teased apart. * Different linear models respond differently to feature correlation and coefficients could significantly vary from one another. * Inspecting coefficients across the folds of a cross-validation loop gives an idea of their stability. * Coefficients are unlikely to have any causal meaning. They tend to be biased by unobserved confounders. * Inspection tools may not necessarily provide insights on the true data generating process. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 17.747 seconds) .. _sphx_glr_download_auto_examples_inspection_plot_linear_model_coefficient_interpretation.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/scikit-learn/scikit-learn/1.4.X?urlpath=lab/tree/notebooks/auto_examples/inspection/plot_linear_model_coefficient_interpretation.ipynb :alt: Launch binder :width: 150 px .. container:: lite-badge .. image:: images/jupyterlite_badge_logo.svg :target: ../../lite/lab/?path=auto_examples/inspection/plot_linear_model_coefficient_interpretation.ipynb :alt: Launch JupyterLite :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_linear_model_coefficient_interpretation.ipynb <plot_linear_model_coefficient_interpretation.ipynb>` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_linear_model_coefficient_interpretation.py <plot_linear_model_coefficient_interpretation.py>` .. include:: plot_linear_model_coefficient_interpretation.recommendations .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_