
Image by Editor | ChatGPT
Categorical variables contain text or labels instead of numbers. Machine learning models require numerical data to function correctly. Featuretools provides the encode_features function to convert categorical values into numbers. This conversion makes data suitable for analysis and modeling, which helps improve model accuracy and performance.
In this article, we will guide you through using encode_features to encode categorical variables in your dataset.
Setup Your Data and EntitySet
First, let’s create a sample dataset and load it into an EntitySet. Featuretools uses the EntitySet to organize and manage data.
import featuretools as ft
import pandas as pd
# Sample data for the entity set
data = {
"transactions": {
"customer_id": [1, 2, 3, 4, 5, 6],
"product_category": ['Electronics', 'Furniture', 'Clothing', 'Electronics', 'Furniture', 'Clothing'],
"purchase_amount": [250.00, 500.00, 100.00, 150.00, 600.00, 120.00],
"is_member": [True, False, True, False, True, True]
}
}
# Create a pandas dataframe from the data
transactions_df = pd.DataFrame(data["transactions"])
# Ensure the dataframe has an explicit index
transactions_df["transaction_id"] = transactions_df.index
# Create an entity set
es = ft.EntitySet(id="store_data")
# Add the dataframe to the entity set with explicit index
es = es.add_dataframe(dataframe_name="transactions",
dataframe=transactions_df,
index="transaction_id",
logical_types={
"product_category": "Categorical",
"is_member": "Boolean",
})
We create a dataframe called transactions_df with columns for product category (categorical), membership status (boolean), and purchase amount (numeric). Then, we add this dataframe to an EntitySet. This helps Featuretools organize the data and apply automated feature engineering.
Calculate the Feature Matrix
Now, we define the features for our feature matrix. The product_category and is_member columns are categorical and boolean, respectively. The purchase_amount column is numeric. We create a list of Feature objects for these columns.
# Create feature definitions f1 = ft.Feature(es["transactions"].ww["product_category"]) f2 = ft.Feature(es["transactions"].ww["is_member"]) f3 = ft.Feature(es["transactions"].ww["purchase_amount"]) features = [f1, f2, f3] # Create instance ids for the feature matrix ids = [0, 1, 2, 3, 4, 5] # Calculate the feature matrix feature_matrix = ft.calculate_feature_matrix(features, es, instance_ids=ids)
We define the features and pass them to the calculate_feature_matrix function. This function returns a feature matrix based on the data and feature definitions.
Encoding the Features
Now, let’s encode the categorical features in the feature matrix. We will use the encode_features function. Below are several variations of how we can use this function.
Encode All Features
By default, all categorical features in the feature matrix will be encoded.
fm_encoded, f_encoded = ft.encode_features(feature_matrix, features) print(f_encoded)
The product_category feature is one-hot encoded. This creates separate columns for each category: ‘Electronics’, ‘Furniture’, and ‘Clothing’. An ‘unknown’ category is added by default for any missing or unclassified values that might appear in new data.
Limit Encoding to the Top n Categories
You can limit encoding to the top n most frequent categories in each categorical column. For example, let’s encode only the top 2 categories for product_category.
fm_encoded, f_encoded = ft.encode_features(feature_matrix, features, top_n=2) print(f_encoded)
Only the top 2 categories (in this dataset, all categories appear equally, so Featuretools will select two, e.g., ‘Electronics’ and ‘Furniture’) are kept, and any other categories (like ‘Clothing’) are grouped into the ‘unknown’ category.
Exclude Unknown Categories
If we want to exclude the ‘unknown’ category, we can set include_unknown=False. This will only keep the explicitly defined categories in the feature encoding.
fm_encoded, f_encoded = ft.encode_features(feature_matrix, features, include_unknown=False) print(f_encoded)
The ‘unknown’ category is excluded from the encoded features.
Drop the First Category in One-Hot Encoding
To avoid multicollinearity, it is often recommended to drop the first category in one-hot encoding. This can be done by setting drop_first=True.
fm_encoded, f_encoded = ft.encode_features(feature_matrix, features, drop_first=True) print(f_encoded)
The first category (‘Clothing’) is dropped, and only the remaining categories (‘Electronics’ and ‘Furniture’) and the ‘unknown’ category are encoded.
Conclusion
Featuretools simplifies categorical variable encoding. The encode_features function efficiently converts categories into numbers, ensuring the data is ready for machine learning models. One-hot encoding creates separate columns for each category and can handle missing or unclassified values. These techniques help improve model accuracy and performance. Using Featuretools saves time and helps automate feature engineering.
