sklink.compose
Combine relational estimators with scikit-learn transformers of tables.
TransformedTablesEstimatorfits scikit-learn transformers on tables of the database, with the rows the training samples reach, before a relational estimator reads them.
Classes:
- TransformedTablesEstimator: Fit scikit-learn transformers on tables of the database, then an estimator.
sklink.compose.TransformedTablesEstimator
TransformedTablesEstimator(estimator: Any = None, *, transformers: Sequence[tuple[str, Any]] = ()) -> NoneBases: MetaEstimatorMixin, VersionedStateMixin, BaseEstimator
Fit scikit-learn transformers on tables of the database, then an estimator.
Each transformer replaces the columns of one table of the database of estimator, for example to embed a text column with TF-IDF and truncated SVD, scale amounts or bin a numeric column, before estimator reads the table. In fit, a transformer learns only from the rows of its table that the training samples can reach through the relationships: the same rows that the relational estimators read for them, at any depth, and in temporal mode only the rows visible at their cutoffs. It then transforms the whole table, so that predict and transform read the rows of new samples with what was learned in fit. Inside a cross-validation, each fold learns its own statistics, as with a transformer of X in a Pipeline.
The transformer of a table receives the columns of the table that are not keys, not the time column, not id columns and not excluded from features, in the order of the table: a pandas DataFrame, a Polars one if pandas is not installed, and a NumPy array without either, whose columns a ColumnTransformer then selects by position. The keys, the time column, the id and the excluded columns are kept unchanged; the transformer's output columns replace all the others, so a ColumnTransformer with remainder="passthrough" keeps the columns it does not transform. Pass verbose_feature_names_out=False to keep their names: expressions are named after the columns, as in mean(orders.amount). An output that is an array takes its column names from get_feature_names_out, given the input column names. Output columns are typed like the columns of a new Database, and keep the column_types declared for a column of the same name. The output must be dense, with one row per row of the table, and must not reuse the name of a kept column.
Guides: Transform the tables with scikit-learn
Parameters:
- estimator (
estimator): A relational estimator, aPipelineor a meta-estimator that holds one or several of them. Everydatabaseparameter inside it is the sameDatabase, which the transformed database replaces. The rows reachable from the samples are found with the entity, key and time of the relational estimator that receivesX:estimatoritself, the first step of a pipeline, or the estimator a meta-estimator wraps. - transformers (
list of (str, transformer) tuples): Table name and unfitted scikit-learn transformer. Parameters of a transformer are set and tuned as<table>__<parameter>, those of the estimator asestimator__<parameter>. With no transformers, or without a database (flat mode), the estimator is fitted unchanged.
Attributes:
- estimator_ (
estimator): The fitted estimator, which reads the transformed database. - transformers_ (
dict of str to transformer): The fitted transformer of each table. - schema_ (
Schema or None): Part of the schema of the original database that the fitted model needs: the transformed tables in full and what the estimator reads of the others.sklink.rebindchecks a new database against it. - classes_ (
ndarray): Labels of a classifier. - n_features_in_ (
int): Number of columns ofX. - feature_names_in_ (
ndarray of str): Column names ofX, when it has them.
See Also
sklearn.compose.TransformedTargetRegressor : Transform the target.
Notes
The relational configuration of the wrapped model reads through: the attributes database, entity, key and time are those of the relational estimator that receives X, and set_params accepts database (set on every parameter inside the estimator that holds a database, or on that of the estimator that receives X if none does), entity, key, time, allow_reverse_paths and handle_unknown_entity for it. They are not parameters of this class, so get_params and clone do not list them.
Fitting builds a new database with the transformed tables, in which only the output columns of the transformers take new memory: the other tables and the kept columns share their data with the original database. After sklink.rebind to another database, the first call to predict or transform transforms its tables with the fitted transformers, without fitting them again, and the model keeps the result for the next calls. Each transformer receives the columns it was fitted on, in the same order, even if the new table has more columns or orders them differently. A copy, a pickled and loaded model, or set_output transforms the tables again on first use.
Examples:
The transformer of orders receives its columns other than keys, type and amount; position 1, which also works without pandas, selects amount.
>>> from sklearn.compose import ColumnTransformer
>>> from sklearn.preprocessing import KBinsDiscretizer
>>> from sklink.compose import TransformedTablesEstimator
>>> from sklink.datasets import load_shop
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> discretize = KBinsDiscretizer(3, encode="ordinal", strategy="uniform")
>>> bins = ColumnTransformer(
... [("amount", discretize, [1])],
... remainder="passthrough",
... verbose_feature_names_out=False,
... )
>>> model = TransformedTablesEstimator(
... RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=2
... ),
... transformers=[("orders", bins)],
... ).fit(shop.X, shop.y)
>>> model.predict(shop.X[:3]).shape
(3,)Functions:
- decision_function: Decision function of the estimator on the transformed database.
- fit: Fit the transformers on the reachable rows, then the estimator.
- fit_predict: Fit the transformers, then the estimator with its
fit_predict. - fit_transform: Fit the transformers, then the estimator with its
fit_transform. - get_feature_names_out: Output names of the estimator, such as a featurizer.
- get_metadata_routing: Route metadata such as
sample_weightto the estimator. - get_params: Get the parameters, with those of the estimator and the transformers.
- predict: Predict with the estimator on the transformed database.
- predict_log_proba: Log of the class probabilities of the estimator.
- predict_proba: Class probabilities of the estimator on the transformed database.
- score: Score of the estimator on the transformed database.
- score_samples: Sample scores of the estimator, such as an anomaly score.
- set_output: Set the output container of the estimator's
transform. - set_params: Set parameters, including a whole transformer as
<table>. - transform: Transform with the estimator, such as a featurizer, on the new tables.
sklink.compose.TransformedTablesEstimator.classes_
classes_: AnyLabels of the fitted classifier.
sklink.compose.TransformedTablesEstimator.database
database: AnyThe database inside the estimator, or None in flat mode.
sklink.compose.TransformedTablesEstimator.decision_function
decision_function(X: Any) -> AnyDecision function of the estimator on the transformed database.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table.
Returns:
- scores (
ndarray): The estimator's decision function.
sklink.compose.TransformedTablesEstimator.entity
entity: Anyentity of the relational estimator that receives X.
sklink.compose.TransformedTablesEstimator.estimator
estimator = estimatorsklink.compose.TransformedTablesEstimator.feature_names_in_
feature_names_in_: AnyColumn names of X seen in fit, when it had them.
sklink.compose.TransformedTablesEstimator.fit
fit(X: Any, y: Any = None, **fit_params: Any) -> SelfFit the transformers on the reachable rows, then the estimator.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table, as the estimator expects it. - y (
array-like of shape (n_samples,)): Target, passed to the estimator. - **fit_params (
dict): Passed to the estimator'sfit, or routed to it when metadata routing is enabled.
Returns:
- self (
TransformedTablesEstimator): Fitted estimator.
sklink.compose.TransformedTablesEstimator.fit_predict
fit_predict(X: Any, y: Any = None, **fit_params: Any) -> AnyFit the transformers, then the estimator with its fit_predict.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table. - y (
array-like of shape (n_samples,)): Target, passed to the estimator. - **fit_params (
dict): Passed to the estimator'sfit_predict, or routed to it when metadata routing is enabled.
Returns:
- labels (
ndarray of shape (n_samples,)): The estimator's labels ofX, such as clusters.
sklink.compose.TransformedTablesEstimator.fit_transform
fit_transform(X: Any, y: Any = None, **fit_params: Any) -> AnyFit the transformers, then the estimator with its fit_transform.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table. - y (
array-like of shape (n_samples,)): Target, passed to the estimator. - **fit_params (
dict): Passed to the estimator'sfit_transform, or routed to it when metadata routing is enabled.
Returns:
- X_out (
ndarray or DataFrame): The estimator's output forX.
sklink.compose.TransformedTablesEstimator.get_feature_names_out
get_feature_names_out(input_features: Any = None) -> AnyOutput names of the estimator, such as a featurizer.
Parameters:
- input_features (
array-like of str): Passed to the estimator.
Returns:
- names (
ndarray of str): The estimator's output names.
sklink.compose.TransformedTablesEstimator.get_metadata_routing
get_metadata_routing() -> MetadataRouterRoute metadata such as sample_weight to the estimator.
Returns:
- routing (
MetadataRouter): Routing offit,predict,scoreand the other methods that take metadata to the same method ofestimator. Transformers of tables receive no metadata.
sklink.compose.TransformedTablesEstimator.get_params
get_params(deep: bool = True) -> dict[str, Any]Get the parameters, with those of the estimator and the transformers.
Parameters:
- deep (
bool): Also returnestimator__<name>,<table>and<table>__<name>for the estimator and each transformer.
Returns:
- params (
dict): Parameter names mapped to their values.
sklink.compose.TransformedTablesEstimator.key
key: Anykey of the relational estimator that receives X.
sklink.compose.TransformedTablesEstimator.n_features_in_
n_features_in_: intNumber of columns of X seen in fit.
sklink.compose.TransformedTablesEstimator.predict
predict(X: Any, **params: Any) -> AnyPredict with the estimator on the transformed database.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table. - **params (
dict): Passed to the estimator'spredict, or routed to it when metadata routing is enabled.
Returns:
- y_pred (
ndarray of shape (n_samples,)): The estimator's predictions.
sklink.compose.TransformedTablesEstimator.predict_log_proba
predict_log_proba(X: Any) -> AnyLog of the class probabilities of the estimator.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table.
Returns:
- log_proba (
ndarray of shape (n_samples, n_classes)): The estimator's log-probabilities.
sklink.compose.TransformedTablesEstimator.predict_proba
predict_proba(X: Any, **params: Any) -> AnyClass probabilities of the estimator on the transformed database.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table. - **params (
dict): Passed to the estimator'spredict_proba, or routed to it when metadata routing is enabled.
Returns:
- proba (
ndarray of shape (n_samples, n_classes)): The estimator's probabilities, columns in the order ofclasses_.
sklink.compose.TransformedTablesEstimator.score
score(X: Any, y: Any = None, **params: Any) -> floatScore of the estimator on the transformed database.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table. - y (
array-like of shape (n_samples,)): True values. - **params (
dict): Passed to the estimator'sscore, such assample_weight, or routed to it when metadata routing is enabled.
Returns:
- score (
float): The estimator's score.
sklink.compose.TransformedTablesEstimator.score_samples
score_samples(X: Any) -> AnySample scores of the estimator, such as an anomaly score.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table.
Returns:
- scores (
ndarray of shape (n_samples,)): The estimator's scores.
sklink.compose.TransformedTablesEstimator.set_output
set_output(*, transform: str | None = None) -> SelfSet the output container of the estimator's transform.
Parameters:
- transform (
(default, pandas, polars)): Passed to the estimator'sset_output.
Returns:
- self (
TransformedTablesEstimator): The estimator.
sklink.compose.TransformedTablesEstimator.set_params
set_params(**params: Any) -> SelfSet parameters, including a whole transformer as <table>.
Parameters:
- **params (
dict): Parameter names, asget_paramsreturns them, and values.
Returns:
- self (
TransformedTablesEstimator): The estimator.
sklink.compose.TransformedTablesEstimator.time
time: Anytime of the relational estimator that receives X.
sklink.compose.TransformedTablesEstimator.transform
transform(X: Any, **params: Any) -> AnyTransform with the estimator, such as a featurizer, on the new tables.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table. - **params (
dict): Passed to the estimator'stransform, or routed to it when metadata routing is enabled.
Returns:
- X_out (
ndarray or DataFrame): The estimator's output.
sklink.compose.TransformedTablesEstimator.transformers
transformers = transformers