保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。

Revisit consent button We value your privacy We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies. Customise Reject All Accept All Customise Consent Preferences We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below. The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more NecessaryAlways Active Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.

Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI


Write For TDS LinkedInXToggle Search Data Science

How To Perform Feature Selection for Regression Problems

In this article I explain what feature selection is and how to perform it before training a regression model in Python. Serafeim Loukas, PhD August 8, 20206 min read

1. Introduction

What is feature selection ?

Feature selection is the procedure of selecting a subset (some out of all available) of the input variables that are most relevant to the target variable (that we wish to predict). Target variable here **** refers to the** variable that we wish to predic**t. For this article we will assume that we only have numerical input variables and a numerical target for regression predictive modeling. Assuming that, we can easily estimate the relationship between each input variable and the target variable. This relationship can be established by calculating a metric such as the correlation value for example.



Learn this step by step with the interactive AI and Data Scientist and Machine Learning roadmaps.

2. The main numerical feature selection methods

The 2 most famous feature selection techniques that can be used for numerical input data and a numerical target variable are the following:

Correlation is a measure of how two variables change together. The most widely used correlation measure is the Pearson's correlation that assumes a Gaussian distribution of each variable and detects linear relationship between numerical variables. This is done in 2 steps:

  1. The correlation between each regressor and the target is computed, that is, ((X[:, i] - mean(X[:, i])) (y - mean_y)) / (std(X[:, i]) std(y)).
  2. It is converted to an F score then to a p-value.

Mutual information originates from the field of information theory. The idea is that the information gain (typically used in the construction of decision trees) is applied in order to perform the feature selection. Mutual information is calculated between two variables and measures as the reduction in uncertainty for one variable given a known value of the other variable.


3. The dataset

We will use the boston house -prices dataset. This dataset contains information collected by the U.S Census Service concerning housing in the area of Boston Mass. The dataset consists of the following variables:

  1. CRIM - per capita crime rate by town
  2. ZN - proportion of residential land zoned for lots over 25,000 sq.ft.
  3. INDUS - proportion of non-retail business acres per town.
  4. CHAS - Charles River dummy variable (1 if tract bounds river; 0 otherwise)
  5. NOX - nitric oxides concentration (parts per 10 million)
  6. RM - average number of rooms per dwelling
  7. AGE - proportion of owner-occupied units built prior to 1940
  8. DIS - weighted distances to five Boston employment centres
  9. RAD - index of accessibility to radial highways
  10. TAX - full-value property-tax rate per $10,000
  11. PTRATIO - pupil-teacher ratio by town
  12. B - 1000(Bk - 0.63)² where Bk is the proportion of blacks by town
  13. LSTAT - % lower status of the population
  14. MEDV - Median value of owner-occupied homes in $1000's

4. Python Code & Working Example

Let's load and split the dataset into training (70%) and test (30%) sets. text

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_regression
import matplotlib.pyplot as plt
from sklearn.feature_selection import mutual_info_regression

text

# load the data
X, y = load_boston(return_X_y=True)

text

# split into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)

We will use the well known scikit-learn machine library.

Case 1: Feature selection using the Correlation metric

For the correlation statistic we will use the f_regression() function. This function can be used in a feature selection strategy, such as selecting the top k most relevant features (largest values) via the SelectKBest class. text

# feature selection
f_selector = SelectKBest(score_func=f_regression, k='all')

text

# learn relationship from training data
f_selector.fit(X_train, y_train)

text

# transform train input data
X_train_fs = f_selector.transform(X_train)

text

# transform test input data
X_test_fs = f_selector.transform(X_test)

text

# Plot the scores for the features
plt.bar([i for i in range(len(f_selector.scores_))], f_selector.scores_)

text

plt.xlabel("feature index")
plt.ylabel("F-value (transformed from the correlation values)")
plt.show()

Reminder : For the correlation statistic case:

  1. The correlation between each regressor and the target is computed, that is, ((X[:, i] - mean(X[:, i])) (y - mean_y)) / (std(X[:, i]) std(y)).
  2. It is converted to an F score then to a p-value.

Feature Importance plot Feature Importance plot The plot above shows that feature 6 and 13 are more important than the other features. The y-axis represents the F-values that were estimated from the correlation values.


Case 2: Feature selection using the Mutual Information metric

The scikit-learn machine learning library provides an implementation of mutual information for feature selection with numeric input and output variables via the mutual_info_regression() function. text

# feature selection
f_selector = SelectKBest(score_func=mutual_info_regression, k='all')

text

# learn relationship from training data
f_selector.fit(X_train, y_train)

text

# transform train input data
X_train_fs = f_selector.transform(X_train)

text

# transform test input data
X_test_fs = f_selector.transform(X_test)

text

# Plot the scores for the features
plt.bar([i for i in range(len(f_selector.scores_))], f_selector.scores_)

text

plt.xlabel("feature index")
plt.ylabel("Estimated MI value")
plt.show()

Feature Importance plot Feature Importance plot The y-axis represents the estimated mutual information between each feature and the target variable. Compared to the correlation feature selection method we can clearly see many more features scored as being relevant. This may be because of the statistical noise that might exists in the dataset.


5. Conclusion

In this article I have provided two ways in order to perform feature selection. Feature selection is the procedure of selecting a subset (some out of all available) of the input variables that are most relevant to the target variable. Target variable here **** refers to the** variable that we wish to predic**t. Using either the Correlation metric or the Mutual Information metric , we can easily estimate the relationship between each input variable and the target variable. Correlation vs Mutual Information: Compared to the correlation feature selection method we can clearly see many more features scored as being relevant. This may be because of the statistical noise that might exists in the dataset.


You might also like:

LSTM Time-Series Forecasting: Predicting Stock Prices Using An LSTM Model Time-Series Forecasting: Predicting Stock Prices Using An ARIMA Model


Stay tuned & support this effort

If you liked and found this article useful, follow me to be able to see all my new posts. Questions? Post them as a comment and I will reply as soon as possible.


Latest posts

The Best FREE Data Science Resources: FREE Books & Online Courses ROC Curve Explained using a COVID-19 hypothetical example: Binary & Multi-Class Classification... Support Vector Machines (SVM) clearly explained: A python tutorial for classification problems... PCA clearly explained - How, when, why to use it and feature importance: A guide in Python Everything you need to know about Min-Max normalization in Python How Scikit-Learn's StandardScaler works


Get in touch with me

Register Now to Continue Reading

Unlock Towards Data Science with a Free Account

All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account


Written By

Serafeim Loukas, PhD

See all from Serafeim Loukas, PhD Data ScienceFeature SelectionMachine LearningPythonRegression Share This Article

Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS

Related Articles

LLMOps: Production prompt engineering patterns with Hamilton

An overview of the production grade ways to iterate on prompts with Hamilton. Stefan Krawczyk September 13, 202314 min read

Graph RAG, Automated Prompt Engineering, Agent Frameworks, and Other September Must-Reads

Machine Learning The stories that resonated the most with our community in the past month TDS Editors October 3, 20243 min read

Teaching Cars To See - Vehicle Detection Using Machine Learning And Computer Vision

Artificial Intelligence This is the final project of Term 1 of the Udacity Self-Driving Car Engineer Nanodegree. You can find all code related to this project on... Eddie Forson October 25, 201711 min read

From Econometrics to Machine Learning

Machine Learning Why econometrics should be part of your skills Alexandre Warembourg September 8, 20197 min read

Latest picks: 8 Common Pitfalls of Running A/B Tests

Machine Learning Your daily dose of data science TDS Editors February 24, 20211 min read

3 Things You Need To Know Before Working With Images In Machine Learning

Machine Learning Master the basics before taking on computer vision projects Aashish Nair January 10, 20225 min read

Linear Algebra for ML | Matrix, Vector and Data Representation

Machine Learning Starting from using matrix and vector for data representation Destin Gong December 30, 20228 min read

Understand Polars' Lack of Indexes

Switch from Pandas to Polars and forget about indexes Carl Kadie January 6, 20236 min read

Visualizing Audio Pipelines with Streamlit

Machine Learning Examine augmentations right in your browser Pascal Janetzky June 13, 20213 min read

Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network

Recommended Articles

Close