iTranslated by AI
Feature Engineering for Tabular Data to Try in the Early Stages of a Competition
This article is the 4th entry for the Kaggle Advent Calendar 2021.
Introduction
In this article, I have compiled methods for creating features in tabular data competitions, focusing primarily on numerical and categorical data. Rather than advanced content, I will introduce general-purpose feature engineering that can be used even by those participating in a competition for the first time.
Feature Engineering! ...But Before That
About Models
Feature engineering processing may vary depending on the model.
For example, decision trees like Gradient Boosting Decision Trees (GBDT) do not require scaling, and models like LightGBM can handle missing values as they are. On the other hand, neural networks (NN) and linear regression models require scaling and imputation of missing values.
In addition to this, there are cases where decision trees are not good at expressing differences or ratios between features, so they need to be created explicitly, and cases where multicollinearity occurs in linear regression if features with high correlation coefficients are included.
Therefore, it is important to perform feature engineering while understanding the characteristics of the model.
However, for the beginning of a tabular data competition, I think it is best to try LightGBM. For the reasons, u++'s 7 Reasons to "Start with LightGBM" might be helpful.
In addition to the reasons in this article, even when using other models, features created can be easily incorporated into LightGBM, and it can be used for debugging, such as checking for bugs in the feature creation itself or how much it contributes to accuracy.
Convenient Library: xfeat
xfeat implements various encoders for creating features, published by Preferred Networks. Therefore, feature creation code is less likely to become messy, and when participating as a team, you can write readable and shareable code.
Most of the code introduced this time can be written using this xfeat.
Detailed implementation is described in Things I found useful after using the feature engineering library xfeat. Also, Guglilac's I want to use my own function for aggregation in xfeat describes the content when creating your own function as an aggregation function, expanding the scope of implementation.
Feature Engineering
Regarding feature engineering, I will introduce what kind of approaches to take in seven broad frameworks: "(Single) Numerical Data," "(Single) Categorical Data," "Text Data," "Numerical Data × Categorical Data," "Numerical Data × Numerical Data," "Categorical Data × Categorical Data," and "Scaling."
(Single) Numerical Data
Transformations That Preserve Magnitude Relationships
Depending on the model, processing that preserves magnitude relationships may or may not work effectively, and it also relates to scaling, which will be described later.
In decision trees, due to the nature of the model, transformations that preserve magnitude relationships, such as logarithmic transformation, basically do not affect accuracy whether done or not (however, this does not apply when creating new features using the logarithmic-transformed variable). On the other hand, for linear regression models and NNs, logarithmic transformation for distributions with long tails can sometimes work effectively.
On the other hand, as a transformation where magnitude relationships are not preserved, ML_Bear's 【Regularly Updated】 Summary of Tips That Will Surely Be Useful for Kaggle Tabular Data Competitions introduces processing such as extracting the decimal part. With single numerical data, depending on the model used, if you do not create features while being aware of whether magnitude relationships are preserved or not, you will unnecessarily increase the number of dimensions.
Lag Features (In Case of Time Series)
If it is time-series data, using past (or future) data is often effective. Also, for data with spatial structure, including data with distance relationships can sometimes work effectively.
Basically, it is often necessary to create them explicitly for models like GBDT. In the case of NN, it is possible to make the model learn the relationships between time series by using models that can handle time-series data such as LSTM or transformer, but creating lag features can sometimes improve accuracy.
For lag features, it is common to first try shifting (shifting back and forth), taking the difference between the shifted data and the original data (diff), and moving averages. This can be easily implemented using pandas' shift, diff, and rolling methods. Points to note are that you need to check if the data is sorted in time-series order, and you need to use groupby because lag features must be created per series unit.
In particular, for the latter, for example, when there is data like this,
| group | value1 | value2 | |
|---|---|---|---|
| 0 | A | 5 | 31 |
| 1 | A | 6 | 27 |
| 2 | A | 3 | 25 |
| 3 | A | 7 | 21 |
| 4 | B | 3 | 16 |
| 5 | B | 4 | 18 |
| 6 | B | 5 | 16 |
You can create lag features where the data one step before is shifted with the following code.
(Caution is required for models other than GBDT because it will be data that includes missing values)
group = 'group'
feature_cols = ['value1', 'value2']
lag = 1
df = pd.concat([
df, df.groupby(group)[feature_cols].shift(lag).add_prefix(f'shift{lag}_')
], axis=1)
| group | value1 | value2 | shift1_value1 | shift1_value2 | |
|---|---|---|---|---|---|
| 0 | A | 5 | 31 | nan | nan |
| 1 | A | 6 | 27 | 5 | 31 |
| 2 | A | 3 | 25 | 6 | 27 |
| 3 | A | 7 | 21 | 3 | 25 |
| 4 | B | 3 | 16 | nan | nan |
| 5 | B | 4 | 18 | 3 | 16 |
| 6 | B | 5 | 16 | 4 | 18 |
Also, code including diff and rolling can be written as follows.
outputs = [df]
grp_df = df.groupby(group)[feature_cols]
for lag in [-3, -2, -1, 1, 2, 3]:
# shift
outputs.append(grp_df.shift(lag).add_prefix(f'shift{lag}_'))
# diff
outputs.append(grp_df.diff(lag).add_prefix(f'diff{lag}_'))
# rolling
for window in [3]:
tmp_df = grp_df.rolling(window, min_periods=1)
# Take moving average
tmp_df = tmp_df.mean().add_prefix(f'rolling{window}_mean_')
outputs.append(tmp_df.reset_index(drop=True))
df = pd.concat(outputs, axis=1)
(Single) Categorical Data
Categorical data cannot be handled as features as they are and basically need to be converted to numerical data.
(You can also perform binning on numerical data and treat it as a categorical variable.)
One-Hot Encoding
This is a method of creating dummy variables, for example, if a column contains "red, blue, blue, yellow," you create columns for "is red, is blue, is yellow" according to the number of levels, setting it to 1 if true and 0 otherwise. This encoding is used for models other than decision trees.
The problem with this method is that the more categories there are, the more sparse features filled mostly with 0 are created, which can increase training time and the amount of memory required.
In the Kaggle Book, the following are suggested to address this issue:
- Consider encoding methods other than one-hot encoding
- Group them according to some rules to reduce the number of levels of the categorical variable
- Group all infrequent categories into something like "other categories"
Personally, for NNs, I often use an embedding layer to convert them into real-valued vectors (known as the Entity Embedding method). I also often convert them to numbers using Count Encoding, Target Encoding, or aggregate statistics, which I will describe later.
The implementation code can be performed using pd.Categorical and pd.get_dummies as follows. (For details, please refer to Converting categorical variables to dummy variables in pandas (get_dummies).)
train_outputs = [train]
test_outputs = [test]
for col in cat_cols:
categories = set(train[col])
train[col] = pd.Categorical(train[col], categories=categories)
test[col] = pd.Categorical(test[col], categories=categories)
train_outputs.append(pd.get_dummies(train[col]).add_prefix(f'{col}_'))
test_outputs.append(pd.get_dummies(test[col]).add_prefix(f'{col}_'))
train = pd.concat(train_outputs, axis=1)
test = pd.concat(test_outputs, axis=1)
Label Encoding
This is a method of simply converting them to numerical labels. For example, if you have "red, blue, blue, yellow," you replace red with 0, blue with 1, and yellow with 2, converting them to numbers like "0, 1, 1, 2." This is an effective encoding for decision trees like GBDT without increasing the number of dimensions.
The implementation using sklearn's LabelEncoder is as follows.
from sklearn.preprocessing import LabelEncoder
for col in cat_cols:
encoder = LabelEncoder()
encoder.fit(train[col])
train[f'label_{col}'] = encoder.transform(train[col])
test[f'label_{col}'] = encoder.transform(test[col])
Also, it can be implemented simply using list comprehensions.
for col in cat_cols:
encoder = {c: i for i, c in enumerate(train[col].unique())}
train[f'label_{col}'] = train[col].map(encoder)
test[f'label_{col}'] = test[col].map(encoder)
Count Encoding
This is a method of replacing categorical variables with their frequency counts. For example, if you have "red, blue, blue, yellow," since red appears 1 time, blue 2 times, and yellow 1 time, you convert them to numbers like "1, 2, 2, 1."
Implementation can be simplified using pandas' value_counts.
for col in categories_columns:
encoder = train[col].value_counts()
train[f'label_{col}'] = train[col].map(encoder)
test[f'label_{col}'] = test[col].map(encoder)
Target Encoding
This is a method of replacing categorical variables with the expected value of the target variable for each. While it is a method that is expected to be more effective as the cardinality (number of levels) is higher, there is a risk of leakage (where the score during training becomes abnormally high) if the distributions of train and test differ or if processing is not aligned with data splitting during training. Detailed explanations are provided in the Kaggle Book, so please refer to that. Also, hakubishin3's Why is Target Encoding effective? clearly explains that Target Encoding is more efficient than Label Encoding due to the characteristics of GBDT when the cardinality is high.
Implementation is as follows; here, folds is pd.Series data that has been cross-validated and assigned a fold index to each record. (For implementation in xfeat, please refer to Things I found useful after using the feature engineering library xfeat.)
from sklearn.model_selection import KFold
def get_kfold(train, n_splits, seed):
kf = KFold(n_splits=n_splits, shuffle=True, random_state=seed)
fold_series = []
for fold, (idx_train, idx_valid) in enumerate(kf.split(train)):
fold_series.append(pd.Series(fold, index=idx_valid))
fold_series = pd.concat(fold_series).sort_index()
return fold_series
def get_targetencoding(train, test, folds: pd.Series, col: str):
for fold in folds.unique():
idx_train, idx_valid = (folds!=fold), (folds==fold)
group = train[idx_train].groupby(col)['target'].mean().to_dict()
train.loc[idx_valid, f'target_{col}'] = train.loc[idx_valid, col].map(group)
group = train.groupby(col)['target'].mean().to_dict()
test[f'target_{col}'] = test[col].map(group)
return train, test
folds = get_kfold(train, 5, 42)
for col in cat_cols:
train, test = get_targetencoding(train, test, folds, col)
Text Data
Regarding text data, Hidehisa Arai's Natural Language Feature Extraction for Tabular Data is very helpful, so please refer to that.
Personally, when text data is included, I first vectorize it with tf-idf and then use TruncatedSVD to reduce dimensionality for features. Next, I use BERT to embed the data using a pretraining model that fits the task and does not violate any licenses or competition rules, and then reduce the dimensionality of the data using PCA or similar techniques to use as features. (If the feature importance of text data features is high, I sometimes build a model using only the text data and stack it.)
Numerical Data × Categorical Data
Aggregate Statistics
For numerical and categorical data, you can create aggregate statistics as new features.
Aggregation itself is often effective when there are multiple table data sources. For example, in a table where users and purchased items are one-to-many, you can use statistics such as the total amount (sum) of money a user has purchased so far, or the average value (mean) per item, as user features.
On the other hand, it is possible to create aggregate statistics even with a single table, and it can be treated as a form of numerical conversion for categorical data. Therefore, it may not be very effective for categorical variables with a small number of levels.
agg_cols = ['min', 'max', 'mean', 'std']
for col in cat_cols:
grp_df = train.groupby(col)[num_cols].agg(agg_cols)
grp_df.columns = [f'{col}_' + '_'.join(c) for c in grp_df.columns]
train = train.merge(grp_df, on=col, how='left')
test = test.merge(grp_df, on=col, how='left')
Also, you can create new features by calculating the difference between aggregate statistics such as maximum, minimum, median, and average values and the original numerical data. (As in the user and product data example mentioned earlier, by looking at the difference from the average, you can create features such as whether the product is more expensive or cheaper than what the user usually purchases.)
Numerical Data × Numerical Data
Arithmetic Operations Between Numerical Data
By performing arithmetic operations between numerical data, you can create new features.
Especially in GBDT, expressing differences and ratios directly is difficult, so explicitly creating them can improve accuracy.
For example, in atmaCup#10, attributes of art pieces such as height, width, and depth were provided. From this information, you can create new features such as area or volume by simply calculating the product, or the aspect ratio of the piece by dividing them.
If you take the difference between the start and end of the production period, you can create the number of years the production took, and by using other information, you can also create features like how old the creator was when the piece was made.
Regarding feature creation between numerical data, I personally try not to blindly perform arithmetic operations on all numerical data to create new features, but rather to create new features that have some meaning between the numerical data. On the other hand, some people create a large amount of features, train with LightGBM, and use only the variables at the top of the feature importance list.
Categorical Data × Categorical Data
You can create new categorical data by combining existing categorical data and use it as a new feature with the encoding methods introduced so far. However, be careful, as combining categorical data that originally have a high number of levels can result in data that only exists in train or test, or data that has low frequency, which may lead to increased dimensionality without much meaning.
While this can be implemented by straightforwardly combining the data, for exhaustive combinations, you can write it very easily using ConcatCombination from xfeat. (Incidentally, combinations between numerical data can be written using ArithmeticCombinations from xfeat.)
import xfeat
for i in [2, 3]:
concat = xfeat.ConcatCombination(r=i, drop_origin=True)
train = pd.concat([train, concat.fit_transform(train[cat_cols])], axis=1)
test = pd.concat([test, concat.fit_transform(test[cat_cols])], axis=1)
Scaling
Scaling is a method of adjusting the magnitude between each numerical data after creating features. However, it seems that there is no one-size-fits-all scaling method that should be used universally; it depends on the model and the data.
In the first place, when using decision trees, transformations that preserve magnitude relationships—such as taking the logarithm of features or normalizing to a range of 0 to 1—have almost no effect. Since these models learn based on the magnitude of numbers, there is basically no need to perform scaling.
On the other hand, for linear regression, etc., problems arise where variables with larger scales result in smaller regression coefficients, making regularization less effective. Therefore, in most cases, including when using NN, it is better to perform scaling. (As will be mentioned later, there are cases where it is better not to perform scaling for binary variables or sparse vectors.)
StandardScaler
Transforms variables to have a mean of 0 and variance of 1 by subtracting the mean and dividing by the standard deviation. In the case of sparse vectors, this is inappropriate in some cases because subtracting by the mean converts them into dense vectors, while some models are optimized assuming sparse vectors. Also, care must be taken when binary variables are biased, as the standard deviation will be small, which can result in very large values after transformation.
# train: DataFrame for training data
# test: DataFrame for evaluation data
# num_cols: Array of numerical variable column names
# cat_cols: Array of categorical variable column names
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(train[num_cols])
train[num_cols] = scaler.transform(train[num_cols])
test[num_cols] = scaler.transform(test[num_cols])
MinMaxScaler
Transforms the minimum value of each variable to 0 and the maximum to 1 by subtracting the minimum and dividing by the range (max - min). Be aware that if there are extremely large or small values, the scaling may be pulled toward those values, potentially causing adverse effects.
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(train[num_cols])
train[num_cols] = scaler.transform(train[num_cols])
test[num_cols] = scaler.transform(test[num_cols])
RobustScaler
Scaling that can be used when there are extremely large or small values. Recently, many participants used this in the Google Brain - Ventilator Pressure Prediction competition. (Incidentally, accuracy varied significantly depending on the scaling in this competition. Depending on the data characteristics, it may be important to try various scaling methods.)
By default, it transforms the median of each variable to 0 by subtracting the median and dividing by the difference between the 75th and 25th percentile values.
from sklearn.preprocessing import RobustScaler
scaler = RobustScaler(quantile_range=(25.0, 75.0))
scaler.fit(train[num_cols])
train[num_cols] = scaler.transform(train[num_cols])
test[num_cols] = scaler.transform(test[num_cols])
RankGauss
Transforms each variable into a normal distribution by converting it into ranks. It is said to show better performance than other scaling methods in NN models, and can be implemented using QuantileTransformer by setting n_quantiles to a sufficiently large value and specifying output_distribution='normal'.
from sklearn.preprocessing import QuantileTransformer
scaler = QuantileTransformer(
n_quantiles=100,
random_state=42,
output_distribution='normal'
)
scaler.fit(train[num_cols])
train[num_cols] = scaler.transform(train[num_cols])
test[num_cols] = scaler.transform(test[num_cols])
Log Transformation
Log transformation can be effective for variables with a distribution that has a long tail. For data containing 0, use a transformation such as log(x+1), and for data containing negative values, use -log(-x-1). Simply taking the sqrt can also be effective.
As mentioned later, it is sometimes effective to create new features between variables based on data that has been log-transformed. Also, there are usually no particular issues if other scaling is performed after log transformation.
Generalizations of log transformation include the Box-Cox transformation and Yeo-Johnson transformation.
How to proceed with the competition after your first submission
The feature engineering methods introduced so far are general-purpose techniques that can be used in any tabular data competition. However, since these techniques are already used by many participants, to reach the top, you need to do things that other participants are not doing or have not engaged with deeply.
Improving Features
What you can do in feature engineering includes diving deep into EDA (Exploratory Data Analysis) to find clues for creating new features, and incorporating features based on domain knowledge depending on the task.
EDA allows you to investigate relationships between variables by visualizing scatter plots between variables or against the objective variable, or by visualizing scatter plots reduced in dimensions using PCA or t-SNE, with points colored according to the objective variable.
If you can create features that utilize domain knowledge, you can set yourself apart from other participants, although it is difficult to create such features. However, by using methods from similar past competitions and thoroughly investigating papers presented by the competition hosts, you can sometimes make a significant difference compared to other participants.
Improving Models
It might be worth exploring tuning the model's hyperparameters or trying different models altogether. Recently, especially in Kaggle competitions, NNs are often strong even with tabular data, and sometimes it is better to try various NN structures rather than digging deep into features.
On the other hand, there are many cases where models other than GBDT and NN can predict with high accuracy. For example, in the Indoor Location & Navigation competition, the 2nd place team, Reza's solution, used Gaussian process regression and k-nearest neighbors to predict absolute positions with high accuracy in a relatively short time. Using models tailored to the task might allow you to significantly outperform other participants.
Also, by creating multiple models, you can use them for ensembling or stacking. However, if you build a model assuming ensembling from the start, your experimentation speed will drop, so it is better to approach it as something to ensemble at the end.
Competition-Specific Techniques
Discovering a competition-specific effective technique (magic) often leads to significant differences in results. For example, in Indoor Location & Navigation, a method that skillfully combines absolute and relative positions through optimization (saito's Cost Minimization) was strong, and top teams were able to significantly improve accuracy by casting it into discrete optimization.
In Optiver Realized Volatility Prediction, which was still under evaluation at the time of this article's publication, the time-series order was made such that it could not be directly identified by the host, but it was possible to significantly improve accuracy by identifying it or creating features based on temporal distance (a kind of lag feature).
While you can win by discovering such magic, I think it is quite difficult to find them. Perhaps you can discover them by conducting thorough EDA, investigating past competitions, or utilizing knowledge from other fields such as competitive programming (this is something I would like to ask those who consistently place high).
Conclusion
I wrote this article with the hope of summarizing "defensive" feature engineering that can be used more generally, referencing u++'s article Positioning of "Feature Engineering" in Kaggle - In Contribution to "Feature Engineering for Machine Learning".
Those who have participated in competitions many times probably have their own "defensive" feature engineering methods, but for those participating for the first time, this is the area where you are most likely to fall behind right at the start. I hope this article provides some support in that regard.
Discussion