sklink.feature_extraction
Turn relational data into flat feature matrices for any estimator.
Classes:
- RelationalFeaturizer: Turn a population table into a flat matrix of relational features.
sklink.feature_extraction.RelationalFeaturizer
RelationalFeaturizer(database: Database | None = None, *, entity: str | None = None, key: str | int | Sequence[str | int] | None = None, time: str | int | None = None, max_relationship_depth: int = 2, max_lookup_depth: int = 1, primitives: Literal['default'] | Sequence[str] = 'default', conditional: bool = True, max_categories: int = 10, max_features: int | None = None, windows: Sequence[str | dt.timedelta | np.timedelta64] | None = None, include: Sequence[str] | None = None, exclude: Sequence[str] | None = None, allow_reverse_paths: bool = False, passthrough: bool = True, handle_unknown_entity: Literal['error', 'empty'] = 'error', feature_names: Literal['canonical', 'safe'] = 'canonical', n_jobs: int | None = None) -> NoneBases: RelationalMixin, TransformerMixin, BaseEstimator
Turn a population table into a flat matrix of relational features.
Each output column is an expression evaluated on the database for every row of X, such as mean(orders.amount) or count(orders[type == 'express']). The catalog of expressions depends on the schema and the hyperparameters, and on the data only through category vocabularies learned in fit from rows reachable from the training samples. Use it in a Pipeline in front of any tabular estimator.
Time is optional: without time every related row is used; with time, rows of tables with a time column are used only if they happened before the sample's cutoff.
Guides: Relational features, Use with scikit-learn
Parameters:
- database (
Database or None): Relational data.Nonemakes the transformer returnXunchanged (flat mode). - entity (
str): Table ofdatabasethe samples belong to. - key (
(str, int or sequence)): Column(s) ofXwith the entity key, by name or position.Noneuses the columns named like the entity's primary key. - time (
str or int): Column ofXwith the cutoff of each sample.Noneis static mode. - max_relationship_depth (
int): Maximum number of relationships followed from the entity table. - max_lookup_depth (
int): Maximum number of lookups (many-to-one steps after the last table of a path) from the rows of a path to the columns that its category conditions read, such ascount(orders.order_items[products.category == 'toys']), and that are aggregated like the columns of the path's last table, such asmean(orders.order_items.products.price). These lookups reach one row per row and do not count towardsmax_relationship_depth. They continue only the paths of exactlymax_relationship_depthhops, since shorter paths already reach those tables, and never reach the entity table unlessallow_reverse_paths=True.0keeps conditions on the last table of the path. - primitives (
"default" or list of str): Aggregations to apply."default"picks them from each column's type; in temporal mode, numeric columns of tables with a time column also getlast(the latest non-missing value among the rows visible at the cutoff) andtrend(the least-squares slope of the value over time, per day). - conditional (
bool): Also aggregate the numeric columns of a table withmeanandsum(those of them that a list ofprimitivesnames) over the rows of each category of its categorical columns and of the columns its rows look up (seemax_lookup_depth), such assum(orders.amount[type == 'express']). Only columns with at mostmax_categoriescategories among the rows reachable from the training samples get them, so that high-cardinality columns do not multiply the catalog. PassFalsefor a smaller catalog on wide tables. - max_categories (
int): Number of most frequent categories per categorical column that get their owncountandproportionfeatures. - max_features (
int): Raise an error if the catalog has more expressions than this. - windows (
list of str, timedelta or timedelta64): Temporal mode only: also aggregate over these windows before the cutoff. Strings use the duration grammar ofTemporalCutoffSplit: an integer and a unit (W,D,h,min,s,ms,us,ns), possibly combined, such as"30D"or"1D12h". - include (
list of str): Glob patterns over canonical names, table names or relationship names. - exclude (
list of str): Glob patterns over canonical names, table names or relationship names. - allow_reverse_paths (
bool): Allow paths that read rows of other entities through shared tables. - passthrough (
bool): Keep the columns ofXother thankeyandtimeas features. - handle_unknown_entity (
(error, empty)): What to do with keys ofXmissing from the entity table. - feature_names (
(canonical, safe)): Output names: canonical expression names, or short stable aliases. - n_jobs (
int): Reserved for parallel evaluation; results never depend on it.
Attributes:
- expressions_ (
tuple of Expression): Expression of every output column. - categories_ (
dict of str to ndarray): Vocabulary of every categorical output column. - categorical_features_ (
ndarray of bool): Mask of categorical output columns (integer codes). - schema_ (
Schema): Part of the schema the transformer reads. - visibility_ (
Visibility): Visibility policy used infit. - n_features_in_ (
int): Number of columns ofX. - feature_names_in_ (
ndarray of str): Column names ofX, when it has them. - n_features_out_ (
int): Number of output columns.
See Also
sklink.tree.RelationalDecisionTreeClassifier : A tree that learns its questions about the related tables, conditions included, while it grows. sklink.tree.RelationalDecisionTreeRegressor : The same tree for a numeric target. sklink.inspection.describe_expressions : What each output column reads.
Examples:
>>> import numpy as np
>>> from sklink import Database
>>> from sklink.feature_extraction import RelationalFeaturizer
>>> db = Database(
... {
... "customers": {"customer_id": np.array([1, 2])},
... "orders": {
... "order_id": np.array([10, 11, 12]),
... "customer_id": np.array([1, 1, 2]),
... "amount": np.array([5.0, 7.0, 3.0]),
... },
... },
... primary_keys={"customers": "customer_id", "orders": "order_id"},
... relationships=[("orders.customer_id", "customers.customer_id")],
... )
>>> feat = RelationalFeaturizer(db, entity="customers", key=0)
>>> X = np.array([[1], [2], [1]])
>>> feat.fit_transform(X)[:, :3]
array([[2., 1., 7.],
[1., 1., 3.],
[2., 1., 7.]])
>>> list(feat.get_feature_names_out()[:3])
['count(orders)', 'exists(orders)', 'max(orders.amount)']Functions:
- fit: Learn the catalog of expressions and the category vocabularies.
- get_feature_names_out: Names of the output columns.
- set_output: Set the output container of
transformandfit_transform. - transform: Evaluate the learned expressions for every row of
X.
sklink.feature_extraction.RelationalFeaturizer.allow_reverse_paths
allow_reverse_paths = allow_reverse_pathssklink.feature_extraction.RelationalFeaturizer.conditional
conditional = conditionalsklink.feature_extraction.RelationalFeaturizer.database
database = databasesklink.feature_extraction.RelationalFeaturizer.entity
entity = entitysklink.feature_extraction.RelationalFeaturizer.exclude
exclude = excludesklink.feature_extraction.RelationalFeaturizer.expressions
expressions: tuple[Expression, ...]Alias of expressions_ for introspection tools.
sklink.feature_extraction.RelationalFeaturizer.feature_names
feature_names = feature_namessklink.feature_extraction.RelationalFeaturizer.fit
fit(X: Any, y: Any = None) -> SelfLearn the catalog of expressions and the category vocabularies.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table: entity key, optional cutoff and sample features. - y (
None): Ignored.
Returns:
- self (
RelationalFeaturizer): Fitted transformer.
sklink.feature_extraction.RelationalFeaturizer.get_feature_names_out
get_feature_names_out(input_features: Any = None) -> np.ndarrayNames of the output columns.
Parameters:
- input_features (
array-like of str): Names of the columns ofX. IfXhad column names infit, they must be equal tofeature_names_in_. Otherwise they name the passed-through columns instead ofx0,x1, ... (safe aliases always derive from the canonical names).
Returns:
- names (
ndarray of str): Canonical expression names, orf{n}_{hash}aliases withfeature_names="safe".
Raises:
ValueError: Ifinput_featuresdoes not have one name per column ofX, or differs fromfeature_names_in_.
sklink.feature_extraction.RelationalFeaturizer.handle_unknown_entity
handle_unknown_entity = handle_unknown_entitysklink.feature_extraction.RelationalFeaturizer.include
include = includesklink.feature_extraction.RelationalFeaturizer.key
key = keysklink.feature_extraction.RelationalFeaturizer.max_categories
max_categories = max_categoriessklink.feature_extraction.RelationalFeaturizer.max_features
max_features = max_featuressklink.feature_extraction.RelationalFeaturizer.max_lookup_depth
max_lookup_depth = max_lookup_depthsklink.feature_extraction.RelationalFeaturizer.max_relationship_depth
max_relationship_depth = max_relationship_depthsklink.feature_extraction.RelationalFeaturizer.n_jobs
n_jobs = n_jobssklink.feature_extraction.RelationalFeaturizer.passthrough
passthrough = passthroughsklink.feature_extraction.RelationalFeaturizer.primitives
primitives = primitivessklink.feature_extraction.RelationalFeaturizer.schema_
schema_: Schema | Nonesklink.feature_extraction.RelationalFeaturizer.set_output
set_output(*, transform: str | None = None) -> SelfSet the output container of transform and fit_transform.
Parameters:
- transform (
(default, pandas, polars)):"pandas"and"polars"give a DataFrame with native categorical and nullable boolean columns;"default"gives thefloat64array;Noneleaves the configuration unchanged.
Returns:
- self (
RelationalFeaturizer): The transformer.
sklink.feature_extraction.RelationalFeaturizer.time
time = timesklink.feature_extraction.RelationalFeaturizer.transform
transform(X: Any) -> AnyEvaluate the learned expressions for every row of X.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- X_out (
ndarray or DataFrame of shape (n_samples, n_features_out_)): By default, features asfloat64withNaNfor missing values; categorical columns hold codes intocategories_. Withset_output(transform="pandas")or"polars", a DataFrame whose categorical columns have a native categorical dtype with the labels ofcategories_and whose boolean columns are nullable booleans. Polars categoricals hold strings, so non-string labels are written withstrthere.
sklink.feature_extraction.RelationalFeaturizer.windows
windows = windows