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 Linear Models 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, Xi and the
target, y, assuming that all the other features remain constant
(). This is different
from plotting versus 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.
We will use data from the “Current Population Survey” from 1985 to predict wage as a function of
various features such as experience, age, or education.
# Authors: The scikit-learn developers# SPDX-License-Identifier: BSD-3-Clause
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.
First, let’s get some insights by looking at the variables’ distributions and
at the pairwise relationships between them. Only numerical
variables will be used. In the following plot, each dot represents a sample.
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 machine-learning pipeline
To design our machine-learning pipeline, we first manually
check the type of data that we are dealing with:
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.
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Then we check the performance of the computed model by plotting its predictions
against the actual values on the test set, and by computing
the median absolute error.
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.
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 1 year in AGE
means a decrease of 0.030867 dollars/hour, while an increase of
1 year in EDUCATION means an increase of 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.
coefs.plot.barh(figsize=(9,7))plt.title("Ridge model, small regularization")plt.axvline(x=0,color=".5")
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.
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 after this is equivalent to normalize
numerical variables to their standard deviation,
as y=∑coefi×Xi=∑(coefi×stdi)×(Xi/stdi).
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.
Now that the coefficients have been scaled, we can safely compare them.
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.
Interpreting coefficients: being cautious about causality
Linear models are a great tool for measuring statistical association, but we
should be cautious when making statements about causality, after all
correlation doesn’t always imply causation. This is particularly difficult in
the social sciences because the variables we observe only function as proxies
for the underlying causal process.
In our particular case we can think of the EDUCATION of an individual as a
proxy for their professional aptitude, the real variable we’re interested in
but can’t observe. We’d certainly like to think that staying in school for
longer would increase technical competency, but it’s also quite possible that
causality goes the other way too. That is, those who are technically
competent tend to stay in school for longer.
An employer is unlikely to care which case it is (or if it’s a mix of both),
as long as they remain convinced that a person with more EDUCATION is better
suited for the job, they will be happy to pay out a higher WAGE.
This confounding of effects becomes problematic when thinking about some
form of intervention e.g. government subsidies of university degrees or
promotional material encouraging individuals to take up higher education.
The usefulness of these measures could end up being overstated, especially if
the degree of confounding is strong. Our model predicts a 0.054699
increase in hourly wage for each year of education. The actual causal effect
might be lower because of this confounding.
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).
If coefficients vary significantly when changing the input dataset
their robustness is not guaranteed, and they should probably be interpreted
with caution.
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.
The estimation of the EXPERIENCE coefficient now shows a much reduced
variability. EXPERIENCE remains important for all models trained during
cross-validation.
Preprocessing numerical variables
As said above (see “The machine-learning 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.
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
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. RidgeCV applies cross validation
in order to determine which value of the regularization parameter (alpha)
is best suited for prediction.
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
First we check which value of α has been selected.
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 Ridge regression and classification 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 previous one.
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 Lasso User Guide section) estimates sparse
coefficients. LassoCV applies cross
validation in order to determine which value of the regularization parameter
(alpha) is best suited for the model estimation.
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.
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 (OVB) on the EDUCATION
coefficient, thereby exaggerating the effect of education on wages.
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.
Interpreting causality is difficult when there are confounding effects. If
the relationship between two variables is also affected by something
unobserved, we should be careful when making conclusions about causality.
Total running time of the script: (0 minutes 13.587 seconds)
drop: {'first', 'if_binary'} or an array-like of shape (n_features,), default=None
Specifies a methodology to use to drop one of the categories per feature. This is useful in situations where perfectly collinear features cause problems, such as when feeding the resulting data into an unregularized linear regression model.
However, dropping one category breaks the symmetry of the original representation and can therefore induce a bias in downstream models, for instance for penalized linear classification or regression models.
- None : retain all features (the default). - 'first' : drop the first category in each feature. If only one category is present, the feature will be dropped entirely. - 'if_binary' : drop the first category in each feature with two categories. Features with 1 or more than 2 categories are left intact. - array : ``drop[i]`` is the category in feature ``X[:, i]`` that should be dropped.
When `max_categories` or `min_frequency` is configured to group infrequent categories, the dropping behavior is handled after the grouping.
.. versionadded:: 0.21 The parameter `drop` was added in 0.21.
.. versionchanged:: 0.23 The option `drop='if_binary'` was added in 0.23.
.. versionchanged:: 1.1 Support for dropping infrequent categories.
drop: {'first', 'if_binary'} or an array-like of shape (n_features,), default=None
Specifies a methodology to use to drop one of the categories per feature. This is useful in situations where perfectly collinear features cause problems, such as when feeding the resulting data into an unregularized linear regression model.
However, dropping one category breaks the symmetry of the original representation and can therefore induce a bias in downstream models, for instance for penalized linear classification or regression models.
- None : retain all features (the default). - 'first' : drop the first category in each feature. If only one category is present, the feature will be dropped entirely. - 'if_binary' : drop the first category in each feature with two categories. Features with 1 or more than 2 categories are left intact. - array : ``drop[i]`` is the category in feature ``X[:, i]`` that should be dropped.
When `max_categories` or `min_frequency` is configured to group infrequent categories, the dropping behavior is handled after the grouping.
.. versionadded:: 0.21 The parameter `drop` was added in 0.21.
.. versionchanged:: 0.23 The option `drop='if_binary'` was added in 0.23.
.. versionchanged:: 1.1 Support for dropping infrequent categories.
drop: {'first', 'if_binary'} or an array-like of shape (n_features,), default=None
Specifies a methodology to use to drop one of the categories per feature. This is useful in situations where perfectly collinear features cause problems, such as when feeding the resulting data into an unregularized linear regression model.
However, dropping one category breaks the symmetry of the original representation and can therefore induce a bias in downstream models, for instance for penalized linear classification or regression models.
- None : retain all features (the default). - 'first' : drop the first category in each feature. If only one category is present, the feature will be dropped entirely. - 'if_binary' : drop the first category in each feature with two categories. Features with 1 or more than 2 categories are left intact. - array : ``drop[i]`` is the category in feature ``X[:, i]`` that should be dropped.
When `max_categories` or `min_frequency` is configured to group infrequent categories, the dropping behavior is handled after the grouping.
.. versionadded:: 0.21 The parameter `drop` was added in 0.21.
.. versionchanged:: 0.23 The option `drop='if_binary'` was added in 0.23.
.. versionchanged:: 1.1 Support for dropping infrequent categories.