sklink.cluster
Clustering of the entities of a multi-table database.
RelationalKMeansruns k-means on standardized relational features.RelationalClusteringTreegrows a tree whose leaves are clusters defined by questions about the related tables.
Classes:
- RelationalClusteringTree: Clustering tree: clusters of entities defined by relational questions.
- RelationalKMeans: K-means clustering of the entities of a multi-table database.
sklink.cluster.RelationalClusteringTree
RelationalClusteringTree(database: Database | None = None, *, entity: str | None = None, key: str | int | Sequence[str | int] | None = None, time: str | int | None = None, n_clusters: int = 8, max_depth: int | None = None, min_samples_split: int | float = 2, min_samples_leaf: int | float = 1, min_weight_fraction_leaf: float = 0.0, max_features: int | float | Literal['sqrt', 'log2'] | None = None, min_impurity_decrease: float = 0.0, n_components: int | float | None = None, max_relationship_depth: int = 2, max_lookup_depth: int = 1, primitives: Literal['default'] | Sequence[str] = 'default', max_conditions: int = 1, max_bins: int = 255, max_condition_bins: int = 32, max_categories: int = 32, record_candidates: int = 5, allow_reverse_paths: bool = False, handle_unknown_entity: Literal['error', 'empty'] = 'error', random_state: int | np.random.RandomState | None = None) -> NoneBases: ClusterMixin, BaseRelationalTree
Clustering tree: clusters of entities defined by relational questions.
A top-down clustering tree (Blockeel, De Raedt and Ramon, 1998) whose questions are those of RelationalDecisionTreeRegressor: aggregates of related tables, optionally under learned conditions, such as count(orders[amount > 100]) > 2. Instead of a target, every split reduces the k-means objective of the samples described by the relational features of RelationalFeaturizer (standardized, as in RelationalKMeans). The tree grows best-first until it has n_clusters leaves; each leaf is a cluster, and the path from the root reads as its definition. With database=None it splits on the columns of X alone.
Guides: Cluster entities, Case study: segments and anomalies
Parameters:
- database (
Database): Related tables.Noneclusters the columns ofXalone. - entity (
str): Table whose rows are the samples; required with a database. - key (
(str, int or sequence)): Column(s) ofXholding the entity key. - time (
str or int): Column ofXwith the cutoff of each sample;Noneis static. - n_clusters (
int): Maximum number of clusters (leaves). The tree has fewer when no further split is allowed. - max_depth (
int): Maximum depth of the tree. - min_samples_split (
int or float): Minimum number of samples to split a node. - min_samples_leaf (
int or float): Minimum number of samples in each cluster. - min_weight_fraction_leaf (
float): Minimum fraction of the total sample weight in each cluster. - max_features (
(int, float, {sqrt, log2} or None)): Number of candidate groups tried at each node (see the tree). - min_impurity_decrease (
float): A node is split only if the weighted decrease of the within-cluster variance reaches this. - n_components (
(int, float or None)): Describe the samples by this many principal components of the standardized features (a float in(0, 1): enough to explain that fraction of the variance). An int is at most the number of standardized features and of samples of positive weight.Nonekeeps every standardized feature. - max_relationship_depth (
int): Maximum number of relationship hops of a path, in the questions and in the features that describe the samples. - max_lookup_depth (
int): Maximum number of lookups (many-to-one steps after the last table of a path, not counted bymax_relationship_depth) from the rows a path aggregates to the columns its conditions read and that are aggregated like the columns of the path's last table, such asmean(orders.order_items.products.price), in the questions and in the features that describe the samples (see the tree). - primitives (
"default" or sequence of str): Primitives of the unconditioned aggregates, in the questions and in the features that describe the samples. - max_conditions (
int): Conditions learned inside an aggregate: 0, 1 or 2. The default is 1, not 2 as in the supervised trees: a clustering tree is read as a description of its clusters, and one condition per aggregate keeps its questions short. - max_bins (
int): Thresholds per base feature. - max_condition_bins (
int): Candidate cuts per numeric condition column before refinement. - max_categories (
int): Most frequent categories tried in conditions, and that get their own features in the description of the samples. - record_candidates (
int): Number of best questions kept for each split node (see the tree). - allow_reverse_paths (
bool): Allow paths that read rows of other entities through shared tables. - handle_unknown_entity (
(error, empty)): What to do with keys that are not in the entity table. - random_state (
(int, RandomState or None)): Controls the sampling ofmax_features.
Attributes:
- labels_ (
ndarray of shape (n_samples,)): Cluster of every row ofXseen infit. - n_clusters_ (
int): Number of clusters, the leaves of the tree. - cluster_centers_ (
ndarray of shape (n_clusters_, n_embedding_features)): Centroid of each cluster in the embedding space. - inertia_ (
float): Weighted sum of squared distances of the training rows to the centroid of their cluster. It is comparable with theinertia_ofRelationalKMeanswhen both describe the samples with the same features: sameprimitives,max_relationship_depth,max_lookup_depth,max_categories(whose default differs, 32 here and 10 there) andn_components, withconditional(False, as here),windows,includeandexcludeof the k-means left at their defaults. - leaf_to_cluster_ (
ndarray of shape (node_count,)): Cluster of every node oftree_,-1for split nodes. Clusters are numbered in the order in whichexport_textprints their leaves. - tree_ (
RelationalTree): Fitted tree structure;valueholds the centroids. - expressions_ (
tuple of Expression): Questions used by the tree. - featurizer_ (
RelationalFeaturizer): Fitted featurizer that describes the samples. - embedding_feature_names_ (
ndarray of str): Names of the columns ofcluster_centers_(seeRelationalKMeans). - feature_importances_ (
ndarray of shape (n_features_in_,)): Impurity-based importance per column ofX. - expression_importances_ (
dict): Importance per canonical expression name. - schema_ (
Schema or None): Part of the database schema the model reads. - visibility_ (
Visibility): Visibility rules used during fit. - n_features_in_ (
int): Number of columns ofX. - feature_names_in_ (
ndarray of shape (n_features_in_,)): Column names ofXwhen it has them.
See Also
sklink.cluster.RelationalKMeans : K-means on the same features, with clusters that are not restricted to the cells of a tree. sklink.inspection.export_text : Print the definition of every cluster.
Notes
A split is chosen by the decrease of the within-cluster sum of squares, the k-means objective, so the tree is a divisive k-means whose clusters are cells of questions about the database. It optimizes that objective less well than RelationalKMeans, and in exchange each cluster has a short definition. Single outliers can make the largest decrease; raise min_samples_leaf for clusters of a useful size.
Every candidate split sums each standardized feature over the samples, so the fit takes longer with more features: tens of them make it slower than a supervised tree on the same rows. A float n_components such as 0.9 usually keeps far fewer columns.
References
H. Blockeel, L. De Raedt and J. Ramon, "Top-down induction of clustering trees", Proceedings of the 15th International Conference on Machine Learning, 1998.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.cluster import RelationalClusteringTree
>>> shop = load_shop()
>>> model = RelationalClusteringTree(
... shop.database, entity="customers", key=0, n_clusters=3,
... min_samples_leaf=4,
... ).fit(shop.X)
>>> model.n_clusters_
3Functions:
- apply: Index of the leaf that each sample ends up in.
- decision_path: Nodes that each sample goes through.
- fit: Grow the clustering tree.
- get_depth: Depth of the tree (a single leaf has depth 0).
- get_n_leaves: Return the number of leaves of the tree.
- predict: Cluster of every row of
X: the leaf it reaches.
sklink.cluster.RelationalClusteringTree.allow_reverse_paths
allow_reverse_paths = allow_reverse_pathssklink.cluster.RelationalClusteringTree.apply
apply(X: Any) -> npt.NDArray[np.int64]Index of the leaf that each sample ends up in.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- X_leaves (
ndarray of shape (n_samples,)): Node index of the leaf of each sample.
sklink.cluster.RelationalClusteringTree.condition_penalty
condition_penalty = condition_penaltysklink.cluster.RelationalClusteringTree.criterion
criterion: strSplit criterion of the tree machinery (fixed).
sklink.cluster.RelationalClusteringTree.database
database = databasesklink.cluster.RelationalClusteringTree.decision_path
decision_path(X: Any) -> scipy.sparse.csr_arrayNodes that each sample goes through.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- indicator (
sparse array of shape (n_samples, n_nodes)): Nonzero entries mark the visited nodes.
sklink.cluster.RelationalClusteringTree.entity
entity = entitysklink.cluster.RelationalClusteringTree.fit
fit(X: Any, y: Any = None, sample_weight: Any = None) -> SelfGrow the clustering tree.
With scikit-learn 1.9 or later, callbacks set with set_callbacks follow the fit: every node is a subtask named "node", as in RelationalDecisionTreeRegressor.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table: entity key, optional cutoff and sample features. - y (
None): Ignored. - sample_weight (
array-like of shape (n_samples,)): Sample weights. A row of weight zero learns nothing, as if it were not inX, but still gets a label.
Returns:
- self (
RelationalClusteringTree): Fitted estimator.
sklink.cluster.RelationalClusteringTree.get_depth
get_depth() -> intDepth of the tree (a single leaf has depth 0).
Returns:
- depth (
int): Maximum distance between the root and a leaf.
sklink.cluster.RelationalClusteringTree.get_n_leaves
get_n_leaves() -> intReturn the number of leaves of the tree.
Returns:
- n_leaves (
int): Number of leaves.
sklink.cluster.RelationalClusteringTree.handle_unknown_entity
handle_unknown_entity = handle_unknown_entitysklink.cluster.RelationalClusteringTree.key
key = keysklink.cluster.RelationalClusteringTree.max_bins
max_bins = max_binssklink.cluster.RelationalClusteringTree.max_categories
max_categories = max_categoriessklink.cluster.RelationalClusteringTree.max_condition_bins
max_condition_bins = max_condition_binssklink.cluster.RelationalClusteringTree.max_conditions
max_conditions = max_conditionssklink.cluster.RelationalClusteringTree.max_depth
max_depth = max_depthsklink.cluster.RelationalClusteringTree.max_features
max_features = max_featuressklink.cluster.RelationalClusteringTree.max_leaf_nodes
max_leaf_nodes: intLeaves of the best-first growth, as the tree machinery checks them.
n_clusters=1 is applied in fit.
sklink.cluster.RelationalClusteringTree.max_lookup_depth
max_lookup_depth = max_lookup_depthsklink.cluster.RelationalClusteringTree.max_relationship_depth
max_relationship_depth = max_relationship_depthsklink.cluster.RelationalClusteringTree.max_search_samples
max_search_samples = max_search_samplessklink.cluster.RelationalClusteringTree.min_impurity_decrease
min_impurity_decrease = min_impurity_decreasesklink.cluster.RelationalClusteringTree.min_samples_leaf
min_samples_leaf = min_samples_leafsklink.cluster.RelationalClusteringTree.min_samples_split
min_samples_split = min_samples_splitsklink.cluster.RelationalClusteringTree.min_weight_fraction_leaf
min_weight_fraction_leaf = min_weight_fraction_leafsklink.cluster.RelationalClusteringTree.n_clusters
n_clusters = n_clusterssklink.cluster.RelationalClusteringTree.n_components
n_components = n_componentssklink.cluster.RelationalClusteringTree.predict
predict(X: Any) -> np.ndarrayCluster of every row of X: the leaf it reaches.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- labels (
ndarray of shape (n_samples,)): Cluster index of every row.
sklink.cluster.RelationalClusteringTree.primitives
primitives = primitivessklink.cluster.RelationalClusteringTree.random_state
random_state = random_statesklink.cluster.RelationalClusteringTree.record_candidates
record_candidates = record_candidatessklink.cluster.RelationalClusteringTree.schema_
schema_: Schema | Nonesklink.cluster.RelationalClusteringTree.time
time = timesklink.cluster.RelationalKMeans
RelationalKMeans(database: Database | None = None, *, entity: str | None = None, key: str | int | Sequence[str | int] | None = None, time: str | int | None = None, n_clusters: int = 8, init: Any = 'k-means++', n_init: Literal['auto'] | int = 'auto', max_iter: int = 300, tol: float = 0.0001, algorithm: Literal['lloyd', 'elkan'] = 'lloyd', n_components: int | float | None = None, max_relationship_depth: int = 2, max_lookup_depth: int = 1, primitives: Literal['default'] | Sequence[str] = 'default', conditional: bool = False, max_categories: int = 10, windows: Sequence[str | dt.timedelta | np.timedelta64] | None = None, include: Sequence[str] | None = None, exclude: Sequence[str] | None = None, allow_reverse_paths: bool = False, handle_unknown_entity: Literal['error', 'empty'] = 'error', random_state: int | np.random.RandomState | None = None) -> NoneBases: ClassNamePrefixFeaturesOutMixin, ClusterMixin, TransformerMixin, VersionedStateMixin, BaseEstimator
K-means clustering of the entities of a multi-table database.
Each sample (a row of X) is described by the relational features of RelationalFeaturizer, such as count(orders), mean(orders.amount) or proportion(orders.order_items[products.category == 'toys']), and by the other columns of X. The features are standardized (categorical ones as indicators, missing values at the training mean), optionally projected on their principal components, and clustered with sklearn.cluster.KMeans. This is clustering by propositionalization (see References): the relational structure is summarized by aggregates, then a flat clustering algorithm runs on them. With database=None it is k-means on the standardized columns of X.
Guides: Cluster entities
Parameters:
- database (
Database): Related tables.Noneclusters the columns ofXalone. - entity (
str): Table whose rows are the samples; required with a database. - key (
(str, int or sequence)): Column(s) ofXholding the entity key. - time (
str or int): Column ofXwith the cutoff of each sample;Noneis static. With a cutoff, a sample is described only by rows before it. - n_clusters (
int): Number of clusters. - init (
('k-means++', random)): Initialization of the centers, in the space of the embedding (seesklearn.cluster.KMeans). - n_init (
auto or int): Number of runs with different initial centers; the best is kept. - max_iter (
int): Maximum number of iterations of a run. - tol (
float): Relative tolerance on the change of the centers to declare convergence. - algorithm (
(lloyd, elkan)): K-means algorithm. - n_components (
(int, float or None)): Project the standardized features on this many principal components (a float in(0, 1): enough components to explain that fraction of the variance) before clustering. An int is at most the number of standardized features and of samples of positive weight.Nonekeeps every standardized feature. - 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, not counted bymax_relationship_depth) from the rows of a path to the columns that its category conditions read and that are aggregated like the columns of the path's last table, such asmean(orders.order_items.products.price)(see the featurizer). - primitives (
"default" or list of str): Aggregations to apply."default"picks them from each column's type. - conditional (
bool): Also aggregate numeric columns over the rows of each frequent category, asRelationalFeaturizerdoes by default. Off by default here: these aggregates add many columns correlated with the unconditioned ones, which then weigh several times in the distances between samples. - max_categories (
int): Number of most frequent categories per categorical column that get their owncountandproportionfeatures. - windows (
list of str, timedelta or timedelta64): Temporal mode only: also aggregate over these windows before the cutoff. - include (
list of str): Glob patterns over canonical names, table names or relationship names that select the features. - exclude (
list of str): Glob patterns over canonical names, table names or relationship names that select the features. - allow_reverse_paths (
bool): Allow paths that read rows of other entities through shared tables. - handle_unknown_entity (
(error, empty)): What to do with keys ofXmissing from the entity table. - random_state (
(int, RandomState or None)): Controls the initialization of the centers.
Attributes:
- cluster_centers_ (
ndarray of shape (n_clusters, n_embedding_features)): Centers in the embedding space, whose columns are named byembedding_feature_names_. - labels_ (
ndarray of shape (n_samples,)): Cluster of every row ofXseen infit. - inertia_ (
float): Weighted sum of squared distances of the training rows to their center. - n_iter_ (
int): Iterations of the best run. - featurizer_ (
RelationalFeaturizer): Fitted featurizer that describes the samples. - embedding_feature_names_ (
ndarray of str): Names of the columns ofcluster_centers_: a featurizer column, or"name == label"for the indicator of a category, whenn_componentsisNone;"pc0","pc1", ... otherwise. - explained_variance_ratio_ (
ndarray of shape (n_components,)): Fraction of the variance of each principal component; only withn_components. - expressions_ (
tuple of Expression): Expressions of the featurizer columns. - schema_ (
Schema or None): Part of the database schema the model reads. - visibility_ (
Visibility): Visibility rules used during fit. - n_features_in_ (
int): Number of columns ofX. - feature_names_in_ (
ndarray of str): Column names ofX, when it has them.
See Also
sklink.cluster.RelationalClusteringTree : Clusters described by questions about the related tables, such as count(orders) > 3.
Notes
Every feature has the same weight after standardization, so a table with many columns has more say in the distance than a table with few. Narrow the features with include or exclude, or set n_components to merge redundant aggregates.
References
G. Anderson and B. Pfahringer, "Clustering relational data based on randomized propositionalization", Inductive Logic Programming, 2007.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.cluster import RelationalKMeans
>>> shop = load_shop()
>>> model = RelationalKMeans(
... shop.database, entity="customers", key=0, n_clusters=3, random_state=0
... ).fit(shop.X)
>>> model.labels_.shape
(24,)Functions:
- fit: Compute the clusters.
- fit_transform: Fit, then return the distances of every row to every center.
- predict: Closest center of every row of
X. - score: Opposite of the inertia of
Xwith the fitted centers. - transform: Distances of every row of
Xto every center.
sklink.cluster.RelationalKMeans.algorithm
algorithm = algorithmsklink.cluster.RelationalKMeans.allow_reverse_paths
allow_reverse_paths = allow_reverse_pathssklink.cluster.RelationalKMeans.conditional
conditional = conditionalsklink.cluster.RelationalKMeans.database
database = databasesklink.cluster.RelationalKMeans.entity
entity = entitysklink.cluster.RelationalKMeans.exclude
exclude = excludesklink.cluster.RelationalKMeans.fit
fit(X: Any, y: Any = None, sample_weight: Any = None) -> SelfCompute the clusters.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table: entity key, optional cutoff and sample features. - y (
None): Ignored. - sample_weight (
array-like of shape (n_samples,)): Weight of every row in the standardization and in k-means. A row of weight zero learns nothing, as if it were not inX, but still gets a label.
Returns:
- self (
RelationalKMeans): Fitted estimator.
sklink.cluster.RelationalKMeans.fit_transform
fit_transform(X: Any, y: Any = None, sample_weight: Any = None) -> np.ndarrayFit, then return the distances of every row to every center.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table. - y (
None): Ignored. - sample_weight (
array-like of shape (n_samples,)): Sample weights (seefit).
Returns:
- distances (
ndarray of shape (n_samples, n_clusters)): Euclidean distance to each center in the embedding space.
sklink.cluster.RelationalKMeans.handle_unknown_entity
handle_unknown_entity = handle_unknown_entitysklink.cluster.RelationalKMeans.include
include = includesklink.cluster.RelationalKMeans.init
init = initsklink.cluster.RelationalKMeans.key
key = keysklink.cluster.RelationalKMeans.max_categories
max_categories = max_categoriessklink.cluster.RelationalKMeans.max_iter
max_iter = max_itersklink.cluster.RelationalKMeans.max_lookup_depth
max_lookup_depth = max_lookup_depthsklink.cluster.RelationalKMeans.max_relationship_depth
max_relationship_depth = max_relationship_depthsklink.cluster.RelationalKMeans.n_clusters
n_clusters = n_clusterssklink.cluster.RelationalKMeans.n_components
n_components = n_componentssklink.cluster.RelationalKMeans.n_init
n_init = n_initsklink.cluster.RelationalKMeans.predict
predict(X: Any) -> np.ndarrayClosest center of 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:
- labels (
ndarray of shape (n_samples,)): Cluster index of every row.
sklink.cluster.RelationalKMeans.primitives
primitives = primitivessklink.cluster.RelationalKMeans.random_state
random_state = random_statesklink.cluster.RelationalKMeans.score
score(X: Any, y: Any = None, sample_weight: Any = None) -> floatOpposite of the inertia of X with the fitted centers.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit. - y (
None): Ignored. - sample_weight (
array-like of shape (n_samples,)): Sample weights.
Returns:
- score (
float): Minus the weighted sum of squared distances to the closest center.
sklink.cluster.RelationalKMeans.time
time = timesklink.cluster.RelationalKMeans.tol
tol = tolsklink.cluster.RelationalKMeans.transform
transform(X: Any) -> np.ndarrayDistances of every row of X to every center.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- distances (
ndarray of shape (n_samples, n_clusters)): Euclidean distance to each center in the embedding space.
sklink.cluster.RelationalKMeans.windows
windows = windows