Sitemap
Büşra Sürücü

Büşra Sürücü

Feature Engineering

8 min readJun 26, 2024

--

Press enter or click to view image in full size

Feature Engineering is a fundamental process used in data science and machine learning projects. It involves creating, selecting, and transforming meaningful features or variables from raw data in order to enhance the performance of machine learning models. It is often a crucial step that directly influences the success of a project.

Why is it Important?

The importance of Feature Engineering stems from several key reasons:

  1. Improving Model Performance: Well-chosen or engineered features enable your model to make more accurate predictions, thereby increasing the success rate of your project.
  2. Adapting to Data: Raw data is often not suitable for direct use in machine learning models. Feature Engineering helps by creating features in a format that best represents your data, making it easier for your model to understand.
  3. Addressing Overfitting and Efficiency: Unnecessary or too many features can lead to overfitting or slow down your processes. Effective feature engineering can mitigate or prevent these issues.

The Role of Feature Engineering in Machine Learning Projects

In machine learning projects, Feature Engineering plays the following crucial roles:

  • Data Preparation: Each feature in your dataset directly impacts your model’s ability to train and make predictions. Feature Engineering ensures your data is processed and prepared appropriately.
  • Enhancing Performance: When the right features are selected or engineered, your model’s accuracy and predictive power improve significantly, thereby enhancing overall project success.
  • Pre-processing: Handling tasks such as filling missing values, dealing with outliers, and encoding categorical variables are all part of Feature Engineering, making your dataset suitable for your model.

These core aspects of Feature Engineering play a critical role in the success of a machine learning project. A well-executed feature engineering strategy can elevate your project’s performance and enable your model to make more reliable predictions.

Feature Engineering Techniques

Feature engineering techniques are used for purposes such as improving model performance, making the dataset cleaner and more meaningful, enhancing the model’s generalization ability, and reducing the dimensionality of features. These techniques include:

Missing Value Handling :

The process of handling missing values involves identifying these gaps and deciding on an appropriate method to address them. Here are some common techniques for handling missing values:

Press enter or click to view image in full size
  1. Filling with Mean, Median, or Mode:
  • Mean Imputation: For numerical variables, missing values can be replaced with the mean of the available values. This method is simple but can distort the data distribution if there are many missing values.
  • Median Imputation: For numerical variables, replacing missing values with the median is useful when the data has outliers, as the median is less sensitive to extreme values.
  • Mode Imputation: For categorical variables, missing values can be replaced with the most frequent value (mode).

2. Estimating with a Regression Model:

  • Regression Imputation: This method involves predicting the missing values based on other available features in the dataset. A regression model is trained on the non-missing data, and the model is then used to predict the missing values.
  • Example: If a dataset has missing values for the ‘height’ column, you could use other columns like ‘age’, ‘weight’, and ‘gender’ to predict and fill the missing height values using a regression model.

3. Deleting Rows or Columns:

  • List wise Deletion: This method involves removing rows that contain any missing values. It is straightforward but can lead to significant data loss if many rows have missing values.
  • Column Deletion: If a column has a high percentage of missing values, it might be more practical to remove the entire column, especially if the column is not crucial for analysis.

4. Using Algorithms that Handle Missing Data:

  • Some machine learning algorithms can handle missing values internally. For instance, decision trees and algorithms based on them (like Random Forests) can handle missing data to some extent without requiring imputation.

Outlier Detection and Treatment:

Press enter or click to view image in full size
Source:https://www.cuemath.com/data/outlier/

Outlier detection and treatment are essential steps in data preprocessing to ensure that anomalous data points do not adversely affect the analysis or modeling process. Here’s an explanation of the techniques mentioned:

  1. Z-score Method:
  • The Z-score method identifies outliers by calculating how many standard deviations a data point is away from the mean of the dataset.

Steps:

  • Compute the mean (μ) and standard deviation (σ) of the dataset.
  • Calculate the Z-score for each data point using the formula:

Z=(x-μ)/σ , where x is the data point.

Curtis, A. E., Smith, T. A., Ziganshin, B. A.,et al.(2016). The Mystery of the Z-Score. Thieme Medical Publishers.
Source: Curtis, A. E., Smith, T. A., Ziganshin, B. A.,et al.(2016). The Mystery of the Z-Score. Thieme Medical Publishers.
Press enter or click to view image in full size
Source: Curtis, A. E., Smith, T. A., Ziganshin, B. A.,et al.(2016). The Mystery of the Z-Score. Thieme Medical Publishers.
  • Typically, data points with a Z-score greater than a threshold (commonly 3 or -3) are considered outliers.

2. Interquartile Range (IQR) Method:

  • The IQR method uses the quartiles of the dataset to detect outliers based on the spread of the data.

Steps:

  • Calculate the first quartile (Q1) and third quartile (Q3) of the dataset.
  • Compute the IQR as IQR=Q3−Q1.
  • Define outliers as data points that fall below Q1−1.5×IQR or above Q3+1.5×IQR.

Outlier Treatment Techniques:

Get Büşra Sürücü’s stories in your inbox

Join Medium for free to get updates from this writer.

Once outliers are detected, various methods can be used to handle them:

How to Make Your Machine Learning Models Robust to Outliers - KDnuggets
Source:https://www.r-bloggers.com/2016/12/outlier-detection-and-treatment-with-r/
  1. Imputation or Transformation:
  • For mild outliers, you may choose to impute them with a statistical measure like the mean, median, or mode of the dataset.
  • Alternatively, transforming the data can help normalize the distribution and mitigate the impact of outliers.
  1. Trimming:
  • Trimming involves removing outliers from the dataset completely. This approach is suitable when outliers are suspected to be errors or do not represent the typical behavior of the data.

2. Winsorization:

  • Winsorization replaces extreme outliers with less extreme values. For example, you can replace values above a certain percentile with the value at that percentile.

In summary, outlier detection methods like Z-score and IQR help identify data points that deviate significantly from the norm.

Encoding Categorical Variables:

Encoding categorical variables is the process of converting categorical data into numerical values that can be used for machine learning algorithms.

  1. One Hot Encoding

One-Hot Encoding is the transformation of categorical variables by creating new columns for each unique category. Each column indicates the presence or absence of the respective category, usually taking values of 0 or 1. For example, if the “color” variable has different colors such as red, green, and blue, One-Hot Encoding will create separate columns for these colors.

Press enter or click to view image in full size
Source:https://towardsdatascience.com/encoding-categorical-variables-one-hot-vs-dummy-encoding-6d5b9c46e2db

2. Label Encoding

Label Encoding converts categorical values into numerical format by assigning a unique integer to each category. For instance, if we have a “country” variable with countries like Turkey, Germany, and France, Label Encoding would assign sequential integers starting from 0 to represent each country.

Source: https://ai-ml-analytics.com/categorical-encoding-label-encoding/

The choice of encoding method depends on the characteristics of your dataset and the machine learning algorithm you are using. One-Hot Encoding is typically preferred for nominal (unordered) data, while Label Encoding can be used for ordinal (ordered) data. Proper encoding ensures your dataset is correctly interpreted and your machine learning model produces accurate results.

Scaling and Normalization:

Press enter or click to view image in full size
Source: https://www.mathsisfun.com/data/standard-normal-distribution.html

Scaling and normalization are preprocessing techniques used to standardize the range of independent variables or features of a dataset. This process is essential in machine learning algorithms that are sensitive to the scale of input features. Here are the two main techniques:

  1. Min-Max Scaling (Normalization):

Formula: Xnorm​=​(X − Xmin)​​ / ( Xmax​ − Xmin)

Description: This method rescales the features to a fixed range between 0 and 1. It works by subtracting the minimum value of the feature (X_min) and then dividing by the range of the feature (X_max — X_min).

Usage: Min-Max scaling is sensitive to outliers since it compresses all inliers within a fixed range. It is suitable when the data distribution is not Gaussian(normal) or when the algorithm requires features to be on a 0–1 scale.

2. Standardization (Z-score Normalization):

Formula: Xstd​=(X−μ​) / σ

Description: This method transforms the data to have a mean (μ) of 0 and a standard deviation (σ) of 1. It achieves this by subtracting the mean of the feature (μ) and then dividing by the standard deviation (σ).

Usage: Standardization is less affected by outliers compared to Min-Max scaling. It assumes that the data follows a Gaussian distribution (bell curve distribution) and is suitable when the algorithm assumes zero-centered data.

Key Considerations:

  • Scaling and normalization help improve the performance and convergence of machine learning algorithms.
  • The choice between Min-Max scaling and Standardization depends on the distribution of the data and the requirements of the specific algorithm being used.
  • It’s important to apply scaling and normalization only to the training data and then use the same scaling parameters to transform the test or validation data to avoid data leakage and ensure consistency.

Feature Selection Methods:

Feature selection methods are techniques used to select the most relevant features from a dataset for use in model training. The main goal is to improve the model’s performance by removing irrelevant or redundant features, which can reduce the risk of overfitting, decrease computational cost, and enhance the model’s interpretability.

Source: https://themanoftalent.medium.com/feature-selection-9b1609f1f6b0

Here are some common feature selection methods:

The variance threshold method removes all features whose variance does not meet a certain threshold. This is based on the idea that low-variance features contain less information and are less likely to be useful for model training.

  • Example: If a feature has the same value across all samples, its variance is zero and it can be removed from the dataset.

2. Correlation Analysis:

Correlation analysis involves measuring the correlation between features and the target variable or between pairs of features. Highly correlated features can be redundant, and removing one of the correlated pairs can simplify the model without significant loss of information.

  • Example: Using Pearson correlation to measure the linear relationship between features.

3. Recursive Feature Elimination (RFE):

Recursive Feature Elimination is a wrapper method that works by recursively removing the least important features and building the model on the remaining features. It uses the model’s performance to determine the importance of each feature.

  • Example: Using a linear regression model to eliminate features step by step.

In conclusion feature engineering is a crucial step in the data preprocessing pipeline. It involves various techniques such as handling missing values, detecting and treating outliers, encoding categorical variables, scaling and normalization, and extracting features from text and image data. These techniques help in transforming raw data into a form that is more suitable for modeling.

Feature engineering plays a pivotal role in enhancing model performance and ensuring that the models generalize well to unseen data. By carefully selecting and transforming features, we can improve the accuracy, efficiency, and interpretability of our machine learning models. Effective feature engineering can significantly reduce overfitting, handle data irregularities, and lead to better insights from the data. In essence, mastering feature engineering is key to building robust and high-performing machine learning systems.

Here is the End-to-End Feature Engineering & Data Preprocessing. You can check my Github page:

https://github.com/Bsrsrc/Diabetes-Feature-Engineering/tree/main

Press enter or click to view image in full size

--

--