Migrate from Featuretools to scikit-link
Put your Featuretools tables and relationships in a scikit-link Database. Then replace ft.dfs with RelationalFeaturizer inside your scikit-learn pipeline, and pass the rows you want to predict as X.
Move one prediction task first. Keep its training and test split fixed, rebuild a handful of familiar features, and compare values on the same customer IDs. Then refit your model with the new features and score the held-out rows again.
Find the matching operation
| Featuretools | scikit-link |
|---|---|
ft.EntitySet, add_dataframe, add_relationship | sklink.Database(tables=..., primary_keys=..., relationships=...) |
time_index= on a dataframe | time_columns={"orders": "created_at"} on the Database |
ft.dfs(target_dataframe_name=...) | RelationalFeaturizer(db, entity=..., key=...) |
agg_primitives=[...] | primitives=[...] |
max_depth | max_relationship_depth limits how many relationships scikit-link follows; max_lookup_depth lets conditions and aggregates read parent columns, such as a product's category or price, without an extra hop |
where_primitives and add_interesting_values | conditional=True and max_categories |
cutoff_time data frame | a cutoff column in X and time="cutoff" |
training_window="30 days" | windows=["30D"] adds 30-day features alongside full-history ones |
ft.calculate_feature_matrix(features, ...) | featurizer.transform(X) |
ft.save_features / ft.load_features | Save the fitted featurizer with pickle or joblib after sklink.detach, then use sklink.rebind when loading |
custom AggregationPrimitive | sklink.primitives.register_primitive |
MEAN(orders.amount WHERE type = express) | mean(orders.amount[type == 'express']) |
Set up the example
Install scikit-link with the pandas extra. You can run the scikit-link blocks without Featuretools. To try the Featuretools blocks, use a separate environment with Featuretools 1.31.0, pandas 2.3 and setuptools 80.
python -m pip install "featuretools==1.31.0" "pandas~=2.3.0" "setuptools~=80.0"Both libraries start with the same tables. customers has one row per customer. Each orders row has a customer ID, an order type and an amount. The dates come later, for the cutoff example.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
customers = pd.DataFrame(
{"customer_id": np.arange(200), "region": rng.choice(["north", "south"], 200)}
)
orders = pd.DataFrame(
{
"order_id": np.arange(1500),
"customer_id": rng.integers(0, 200, 1500),
"type": rng.choice(["express", "standard", "pickup"], 1500),
"amount": rng.gamma(2.0, 40.0, 1500).round(2),
}
)Describe the tables
In Featuretools, the tables, their indexes and their relationships go into an EntitySet:
import featuretools as ft
es = ft.EntitySet(id="shop")
es = es.add_dataframe(
dataframe_name="customers", dataframe=customers.copy(), index="customer_id"
)
es = es.add_dataframe(
dataframe_name="orders", dataframe=orders.copy(), index="order_id"
)
es = es.add_relationship("customers", "customer_id", "orders", "customer_id")In scikit-link, the same description goes into one Database. Write the child column first and the parent column second. Here orders.customer_id points to the primary key customers.customer_id.
from sklink import Database
primary_keys = {"customers": "customer_id", "orders": "order_id"}
relationships = [("orders.customer_id", "customers.customer_id")]
db = Database(
tables={"customers": customers, "orders": orders},
primary_keys=primary_keys,
relationships=relationships,
)Generate features
ft.dfs builds a feature matrix for the target table. This example calculates four types of aggregates for all customers.
feature_matrix, feature_defs = ft.dfs(
entityset=es,
target_dataframe_name="customers",
agg_primitives=["count", "sum", "mean", "max"],
trans_primitives=[],
max_depth=2,
)
print(list(feature_matrix.columns)[:5])
# ['region', 'COUNT(orders)', 'MAX(orders.amount)', 'MEAN(orders.amount)', 'SUM(orders.amount)']In scikit-link, X lists the customers you want to make predictions for. Fit a featurizer on those samples to learn the feature definitions, then transform them to get one row of features per customer. The example asks for pandas output so the feature names and categorical types are visible.
from sklink.feature_extraction import RelationalFeaturizer
X = customers[["customer_id"]]
featurizer = RelationalFeaturizer(
db,
entity="customers",
key="customer_id",
primitives=["count", "sum", "mean", "max"],
).set_output(transform="pandas")
features = featurizer.fit_transform(X)
print(features.shape)
print(list(featurizer.get_feature_names_out())[:5])(200, 17)
['region', 'count(orders)', "count(orders[type == 'express'])", "count(orders[type == 'pickup'])", "count(orders[type == 'standard'])"]The feature names differ. Start by matching Featuretools COUNT(orders) to scikit-link count(orders). Use transform to check a few rows with the already fitted feature definitions. The output follows X_check, including the repeated customer ID.
X_check = pd.DataFrame({"customer_id": [7, 2, 7]})
checked = featurizer.transform(X_check)
order_counts = orders.groupby("customer_id").size()
expected = order_counts.reindex(X_check["customer_id"], fill_value=0)
np.testing.assert_array_equal(checked["count(orders)"], expected)The featurizer also adds a count and a proportion for each frequent category, whatever primitives lists (max_categories=0 drops them). To keep a smaller set of columns, use include and exclude with patterns that match the feature names. See Relational features.
For model evaluation, pass the featurizer to a pipeline with your estimator and fit the pipeline on X_train, y_train. In cross-validation, pass the pipeline to the evaluator so the categories and feature definitions are learned within each training fold.
Where primitives and interesting values
Featuretools uses where_primitives to aggregate rows for the chosen values. This example asks for counts and means for express and pickup orders. Featuretools guide to where clauses
es.add_interesting_values(
dataframe_name="orders", values={"type": ["express", "pickup"]}
)
feature_matrix, feature_defs = ft.dfs(
entityset=es,
target_dataframe_name="customers",
agg_primitives=["count", "mean"],
where_primitives=["count", "mean"],
trans_primitives=[],
max_depth=1,
)
# COUNT(orders WHERE type = express), MEAN(orders.amount WHERE type = express), ...In scikit-link, the featurizer aggregates every numeric column with mean and sum within each category of the categorical columns that have at most max_categories categories, by default (conditional=True); with a list of primitives, it uses the ones of the two that the list names. Columns with more categories get only counts of their max_categories most frequent ones. The categories are learned in fit, from the training rows only.
conditional = RelationalFeaturizer(
db,
entity="customers",
key="customer_id",
primitives=["count", "mean"],
max_relationship_depth=1,
).fit(X)
print([name for name in conditional.get_feature_names_out() if name.startswith("mean")])['mean(orders.amount)', "mean(orders.amount[type == 'express'])", "mean(orders.amount[type == 'pickup'])", "mean(orders.amount[type == 'standard'])"]Conditions that combine a category and a threshold, such as express orders above 100, are not listed in advance: a relational decision tree learns them while it grows.
Cutoff times and training windows
If your prediction uses a date, add the order timestamps and a cutoff for each sample. Featuretools takes a cutoff_time DataFrame and can limit the history with training_window. This example rebuilds the Featuretools EntitySet with a time index on orders and asks for rows strictly before the cutoff. Featuretools includes rows at the cutoff by default. Featuretools time handling
orders_at = orders.assign(
created_at=pd.Timestamp("2024-01-01")
+ pd.to_timedelta(rng.integers(0, 365, len(orders)), unit="D")
)es_at = ft.EntitySet(id="shop_at")
es_at = es_at.add_dataframe(
dataframe_name="customers", dataframe=customers.copy(), index="customer_id"
)
es_at = es_at.add_dataframe(
dataframe_name="orders",
dataframe=orders_at.copy(),
index="order_id",
time_index="created_at",
)
es_at = es_at.add_relationship("customers", "customer_id", "orders", "customer_id")
es_at.add_last_time_indexes()
cutoff_times = pd.DataFrame(
{"customer_id": customers["customer_id"], "time": pd.Timestamp("2024-07-01")}
)
feature_matrix, feature_defs = ft.dfs(
entityset=es_at,
target_dataframe_name="customers",
agg_primitives=["count", "sum"],
trans_primitives=[],
cutoff_time=cutoff_times,
training_window="30 days",
include_cutoff_time=False,
)In scikit-link, give Database the order time column and give the featurizer the name of the cutoff column in X. windows=["30D"] adds columns for the 30 days before each cutoff and keeps full-history columns. If you want only the windowed columns, use include=["*|30d)"].
db_at = Database(
tables={"customers": customers, "orders": orders_at},
primary_keys=primary_keys,
relationships=relationships,
time_columns={"orders": "created_at"},
)
X_at = customers[["customer_id"]].assign(cutoff=pd.Timestamp("2024-07-01"))
at_cutoff = RelationalFeaturizer(
db_at,
entity="customers",
key="customer_id",
time="cutoff",
primitives=["count", "sum"],
max_relationship_depth=1,
windows=["30D"],
).fit(X_at)
print(
[name for name in at_cutoff.get_feature_names_out() if name.endswith("|30d)")][:3]
)["count(orders[type == 'express']|30d)", "count(orders[type == 'pickup']|30d)", "count(orders[type == 'standard']|30d)"]Each row of X can have its own cutoff, and the same customer can appear at several cutoffs. Check an event exactly at the cutoff and one exactly at the start of the window when you compare values. scikit-link excludes the first event and includes the second. Use temporal cross-validation if your production model predicts future dates.
Saving feature definitions
ft.save_features stores feature definitions for use with ft.calculate_feature_matrix. In scikit-link, save the fitted featurizer or its pipeline. sklink.detach gives you a copy without the raw tables. After loading it, sklink.rebind gives you a copy attached to a compatible new database, ready to call transform or predict. Follow Save and deploy for the complete workflow.
Differences that change results
- Check the feature set. Column names, condition values and traversal rules can differ. Compare values for the same sample and cutoff before comparing metrics. Check customers with no related rows as well.
- Check category handling. The default featurizer output uses integer codes for categorical features. DataFrame output keeps the categories so downstream models can handle them as labels.
- Check event times. An excluded order also excludes its line items on that path. If an item can arrive later than its order, give the items their own timestamp so the cutoff can exclude that later event.
Replace transform primitives and feature selection
- Transform primitives. Materialize values such as
monthoris_weekendas source columns before building theDatabase. - Feature selection. Fit a scikit-learn selector after the featurizer in the same pipeline as the model.
VarianceThresholddrops constant features, andSelectFromModeluses a fitted model to choose features.