How to Calculate Feature Importance With Python

Feature importance refers to techniques that assign a score to input features based on how useful they are at predicting a target variable.

There are many types and sources of feature importance scores, although popular examples include statistical correlation scores, coefficients calculated as part of linear models, decision trees, and permutation importance scores.

Feature importance scores play an important role in a predictive modeling project, including providing insight into the data, insight into the model, and the basis for dimensionality reduction and feature selection that can improve the efficiency and effectiveness of a predictive model on the problem.

In this tutorial, you will discover feature importance scores for machine learning in pythonAfter completing this tutorial, you will know:Let’s get started.

How to Calculate Feature Importance With PythonPhoto by Bonnie Moreland, some rights reserved.

This tutorial is divided into five parts; they are:Feature importance refers to a class of techniques for assigning scores to input features to a predictive model that indicates the relative importance of each feature when making a prediction.

Feature importance scores can be calculated for problems that involve predicting a numerical value, called regression, and those problems that involve predicting a class label, called classification.

The scores are useful and can be used in a range of situations in a predictive modeling problem, such as:Feature importance scores can provide insight into the dataset.

The relative scores can highlight which features may be most relevant to the target, and the converse, which features are the least relevant.

This may be interpreted by a domain expert and could be used as the basis for gathering more or different data.

Feature importance scores can provide insight into the model.

Most importance scores are calculated by a predictive model that has been fit on the dataset.

Inspecting the importance score provides insight into that specific model and which features are the most important and least important to the model when making a prediction.

This is a type of model interpretation that can be performed for those models that support it.

Feature importance can be used to improve a predictive model.

This can be achieved by using the importance scores to select those features to delete (lowest scores) or those features to keep (highest scores).

This is a type of feature selection and can simplify the problem that is being modeled, speed up the modeling process (deleting features is called dimensionality reduction), and in some cases, improve the performance of the model.

Feature importance scores can be fed to a wrapper model, such as SelectFromModel or SelectKBest, to perform feature selection.

There are many ways to calculate feature importance scores and many models that can be used for this purpose.

Perhaps the simplest way is to calculate simple coefficient statistics between each feature and the target variable.

For more on this approach, see the tutorial:In this tutorial, we will look at three main types of more advanced feature importance; they are:Let’s take a closer look at each.

Before we dive in, let’s confirm our environment and prepare some test datasets.

First, confirm that you have a modern version of the scikit-learn library installed.

This is important because some of the models we will explore in this tutorial require a modern version of the library.

You can check the version of the library you have installed with the following code example:Running the example will print the version of the library.

At the time of writing, this is about version 0.

22.

You need to be using this version of scikit-learn or higher.

Next, let’s define some test datasets that we can use as the basis for demonstrating and exploring feature importance scores.

Each test problem has five important and five unimportant features, and it may be interesting to see which methods are consistent at finding or differentiating the features based on their importance.

We will use the make_classification() function to create a test binary classification dataset.

The dataset will have 1,000 examples, with 10 input features, five of which will be informative and the remaining five will be redundant.

We will fix the random number seed to ensure we get the same examples each time the code is run.

An example of creating and summarizing the dataset is listed below.

Running the example creates the dataset and confirms the expected number of samples and features.

We will use the make_regression() function to create a test regression dataset.

Like the classification dataset, the regression dataset will have 1,000 examples, with 10 input features, five of which will be informative and the remaining five that will be redundant.

Running the example creates the dataset and confirms the expected number of samples and features.

Next, let’s take a closer look at coefficients as importance scores.

Linear machine learning algorithms fit a model where the prediction is the weighted sum of the input values.

Examples include linear regression, logistic regression, and extensions that add regularization, such as ridge regression and the elastic net.

All of these algorithms find a set of coefficients to use in the weighted sum in order to make a prediction.

These coefficients can be used directly as a crude type of feature importance score.

Let’s take a closer look at using coefficients as feature importance for classification and regression.

We will fit a model on the dataset to find the coefficients, then summarize the importance scores for each input feature and finally create a bar chart to get an idea of the relative importance of the features.

We can fit a LinearRegression model on the regression dataset and retrieve the coeff_ property that contains the coefficients found for each input variable.

These coefficients can provide the basis for a crude feature importance score.

This assumes that the input variables have the same scale or have been scaled prior to fitting a model.

The complete example of linear regression coefficients for feature importance is listed below.

Running the example fits the model, then reports the coefficient value for each feature.

The scores suggest that the model found the five important features and marked all other features with a zero coefficient, essentially removing them from the model.

A bar chart is then created for the feature importance scores.

Bar Chart of Linear Regression Coefficients as Feature Importance ScoresThis approach may also be used with Ridge and ElasticNet models.

We can fit a LogisticRegression model on the regression dataset and retrieve the coeff_ property that contains the coefficients found for each input variable.

These coefficients can provide the basis for a crude feature importance score.

This assumes that the input variables have the same scale or have been scaled prior to fitting a model.

The complete example of logistic regression coefficients for feature importance is listed below.

Running the example fits the model, then reports the coefficient value for each feature.

Recall this is a classification problem with classes 0 and 1.

Notice that the coefficients are both positive and negative.

The positive scores indicate a feature that predicts class 1, whereas the negative scores indicate a feature that predicts class 0.

No clear pattern of important and unimportant features can be identified from these results, at least from what I can tell.

A bar chart is then created for the feature importance scores.

Bar Chart of Logistic Regression Coefficients as Feature Importance ScoresNow that we have seen the use of coefficients as importance scores, let’s look at the more common example of decision-tree-based importance scores.

Decision tree algorithms like classification and regression trees (CART) offer importance scores based on the reduction in the criterion used to select split points, like Gini or entropy.

This same approach can be used for ensembles of decision trees, such as the random forest and stochastic gradient boosting algorithms.

Let’s take a look at a worked example of each.

We can use the CART algorithm for feature importance implemented in scikit-learn as the DecisionTreeRegressor and DecisionTreeClassifier classes.

After being fit, the model provides a feature_importances_ property that can be accessed to retrieve the relative importance scores for each input feature.

Let’s take a look at an example of this for regression and classification.

The complete example of fitting a DecisionTreeRegressor and summarizing the calculated feature importance scores is listed below.

Running the example fits the model, then reports the coefficient value for each feature.

The results suggest perhaps three of the 10 features as being important to prediction.

A bar chart is then created for the feature importance scores.

Bar Chart of DecisionTreeRegressor Feature Importance ScoresThe complete example of fitting a DecisionTreeClassifier and summarizing the calculated feature importance scores is listed below.

Running the example fits the model, then reports the coefficient value for each feature.

The results suggest perhaps four of the 10 features as being important to prediction.

A bar chart is then created for the feature importance scores.

Bar Chart of DecisionTreeClassifier Feature Importance ScoresWe can use the Random Forest algorithm for feature importance implemented in scikit-learn as the RandomForestRegressor and RandomForestClassifier classes.

After being fit, the model provides a feature_importances_ property that can be accessed to retrieve the relative importance scores for each input feature.

This approach can also be used with the bagging and extra trees algorithms.

Let’s take a look at an example of this for regression and classification.

The complete example of fitting a RandomForestRegressor and summarizing the calculated feature importance scores is listed below.

Running the example fits the model, then reports the coefficient value for each feature.

The results suggest perhaps two or three of the 10 features as being important to prediction.

A bar chart is then created for the feature importance scores.

Bar Chart of RandomForestRegressor Feature Importance ScoresThe complete example of fitting a RandomForestClassifier and summarizing the calculated feature importance scores is listed below.

Running the example fits the model, then reports the coefficient value for each feature.

The results suggest perhaps two or three of the 10 features as being important to prediction.

A bar chart is then created for the feature importance scores.

Bar Chart of RandomForestClassifier Feature Importance ScoresXGBoost is a library that provides an efficient and effective implementation of the stochastic gradient boosting algorithm.

This algorithm can be used with scikit-learn via the XGBRegressor and XGBClassifier classes.

After being fit, the model provides a feature_importances_ property that can be accessed to retrieve the relative importance scores for each input feature.

This algorithm is also provided via scikit-learn via the GradientBoostingClassifier and GradientBoostingRegressor classes and the same approach to feature selection can be used.

First, install the XGBoost library, such as with pip:Then confirm that the library was installed correctly and works by checking the version number.

Running the example, you should see the following version number or higher.

For more on the XGBoost library, start here:Let’s take a look at an example of XGBoost for feature importance on regression and classification problems.

The complete example of fitting a XGBRegressor and summarizing the calculated feature importance scores is listed below.

Running the example fits the model, then reports the coefficient value for each feature.

The results suggest perhaps two or three of the 10 features as being important to prediction.

A bar chart is then created for the feature importance scores.

Bar Chart of XGBRegressor Feature Importance ScoresThe complete example of fitting an XGBClassifier and summarizing the calculated feature importance scores is listed below.

Running the example fits the model then reports the coefficient value for each feature.

The results suggest perhaps seven of the 10 features as being important to prediction.

A bar chart is then created for the feature importance scores.

Bar Chart of XGBClassifier Feature Importance ScoresPermutation feature importance is a technique for calculating relative importance scores that is independent of the model used.

First, a model is fit on the dataset, such as a model that does not support native feature importance scores.

Then the model is used to make predictions on a dataset, although the values of a feature (column) in the dataset are scrambled.

This is repeated for each feature in the dataset.

Then this whole process is repeated 3, 5, 10 or more times.

The result is a mean importance score for each input feature (and distribution of scores given the repeats).

This approach can be used for regression or classification and requires that a performance metric be chosen as the basis of the importance score, such as the mean squared error for regression and accuracy for classification.

Permutation feature selection can be used via the permutation_importance() function that takes a fit model, a dataset (train or test dataset is fine), and a scoring function.

Let’s take a look at this approach to feature selection with an algorithm that does not support feature selection natively, specifically k-nearest neighbors.

The complete example of fitting a KNeighborsRegressor and summarizing the calculated permutation feature importance scores is listed below.

Running the example fits the model, then reports the coefficient value for each feature.

The results suggest perhaps two or three of the 10 features as being important to prediction.

A bar chart is then created for the feature importance scores.

Bar Chart of KNeighborsRegressor With Permutation Feature Importance ScoresThe complete example of fitting a KNeighborsClassifier and summarizing the calculated permutation feature importance scores is listed below.

Running the example fits the model, then reports the coefficient value for each feature.

The results suggest perhaps two or three of the 10 features as being important to prediction.

A bar chart is then created for the feature importance scores.

Bar Chart of KNeighborsClassifier With Permutation Feature Importance ScoresThis section provides more resources on the topic if you are looking to go deeper.

In this tutorial, you discovered feature importance scores for machine learning in pythonSpecifically, you learned:Do you have any questions? Ask your questions in the comments below and I will do my best to answer.

with just a few lines of scikit-learn codeLearn how in my new Ebook: Machine Learning Mastery With PythonCovers self-study tutorials and end-to-end projects like: Loading data, visualization, modeling, tuning, and much more.

Skip the Academics.

Just Results.

.

Leave a Reply