Use scikit-link with other libraries
scikit-link estimators are scikit-learn estimators, so libraries built around scikit-learn work with them unchanged. These recipes show the ones people ask about most. skrub, SHAP and skops are not dependencies of scikit-link; install the ones you use. The tests_ecosystem session of the project's test suite runs the skrub, SHAP and skops recipes against their latest releases every week.
Setup
from sklearn.model_selection import train_test_split
from sklink.datasets import make_relational_classification
from sklink.ensemble import RelationalRandomForestClassifier
db, X, y = make_relational_classification(300, signal="child_numeric", random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
forest = RelationalRandomForestClassifier(
db, entity="customers", key="customer_id", n_estimators=50, random_state=0
).fit(X_train, y_train)skrub: encode the featurizer's columns
RelationalFeaturizer returns categorical columns, such as the most frequent order type, next to numeric ones. With pandas output, skrub's TableVectorizer encodes them for any estimator:
import skrub
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.pipeline import make_pipeline
from sklink.feature_extraction import RelationalFeaturizer
model = make_pipeline(
RelationalFeaturizer(db, entity="customers", key="customer_id"),
skrub.TableVectorizer(),
HistGradientBoostingClassifier(random_state=0),
).set_output(transform="pandas")
model.fit(X_train, y_train)
print(f"{model.score(X_test, y_test):.3f}")skrub builds the joins and aggregations you describe; scikit-link searches which ones to use. Both fit inside the same pipeline.
SHAP: attribute a prediction to the related rows
SHAP's model-agnostic Explainer works on the columns of X. With a key column only, the whole attribution goes to the key, which stands for all of the customer's related rows:
import pandas as pd
import shap
def probability(Z):
return forest.predict_proba(pd.DataFrame(Z, columns=X.columns))[:, 1]
explainer = shap.Explainer(probability, X_train.to_numpy(dtype=float)[:20])
values = explainer(X_test.to_numpy(dtype=float)[:5])
print(values.values.shape)To see which related rows mattered, such as the express orders above 100, use sklink.inspection.explain, which reports each question or expression on the sample's path: see explain a prediction.
skops and MLflow: save without pickle
skops saves scikit-learn models without running arbitrary code at load time. It is the default format of MLflow's scikit-learn flavor outside Databricks. Detach the tables first, so the file holds only the model. When loading, skops lists the types it does not know yet: check that they are sklink and built-in types before trusting them.
import sklink
import skops.io as sio
blob = sio.dumps(sklink.detach(forest))
untrusted = sio.get_untrusted_types(data=blob)
print(sorted({name.split(".")[0] for name in untrusted}))
loaded = sklink.rebind(sio.loads(blob, trusted=untrusted), db)
print((loaded.predict(X_test) == forest.predict(X_test)).all())sklink.rebind attaches the database to predict from, which can hold this month's data. See save and deploy.
joblib: cross-validate in worker processes
With n_jobs, scikit-learn fits the folds in worker processes. Each worker receives the database once, and the estimators it returns share the caller's Database instead of holding a copy each:
from sklearn.model_selection import cross_validate
result = cross_validate(forest, X_train, y_train, cv=3, n_jobs=2, return_estimator=True)
print(all(model.database is db for model in result["estimator"]))Truescikit-learn inspection
permutation_importance and partial_dependence permute or vary columns of X like any other column. Permuting the key column swaps customers, which measures how much the related rows matter together; see permutation importance.