---
url: /stable/api/sklink.cluster.md
description: >-
  API reference of sklink.cluster. Clustering of the entities of a multi-table
  database.
---

::: v-pre

# `sklink.cluster` {#sklink.cluster}

Clustering of the entities of a multi-table database.

* `RelationalKMeans` runs k-means on standardized relational features.
* `RelationalClusteringTree` grows a tree whose leaves are clusters
  defined by questions about the related tables.

**Classes:**

* [**RelationalClusteringTree**](#sklink.cluster.RelationalClusteringTree): Clustering tree: clusters of entities defined by relational questions.
* [**RelationalKMeans**](#sklink.cluster.RelationalKMeans): K-means clustering of the entities of a multi-table database.

## `sklink.cluster.RelationalClusteringTree` {#sklink.cluster.RelationalClusteringTree}

```python
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) -> None
```

Bases: [ClusterMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.ClusterMixin.html), 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`](./sklink.tree#sklink.tree.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`](./sklink.feature_extraction#sklink.feature_extraction.RelationalFeaturizer)
(standardized, as in [`RelationalKMeans`](#sklink.cluster.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](../tutorials/clustering), [Case study: segments and anomalies](../case-studies/segment-and-flag-accounts)

**Parameters:**

* **database** ([Database](./sklink.database#sklink.database.Database)): Related tables. `None` clusters the columns of `X` alone.
* **entity** ([str](https://docs.python.org/3/library/stdtypes.html#str)): Table whose rows are the samples; required with a database.
* **key** (([str](https://docs.python.org/3/library/stdtypes.html#str), [int](https://docs.python.org/3/library/functions.html#int) or sequence)): Column(s) of `X` holding the entity key.
* **time** ([str](https://docs.python.org/3/library/stdtypes.html#str) or [int](https://docs.python.org/3/library/functions.html#int)): Column of `X` with the cutoff of each sample; `None` is static.
* **n\_clusters** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum number of clusters (leaves). The tree has fewer when no
  further split is allowed.
* **max_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum depth of the tree.
* **min_samples_split** ([int](https://docs.python.org/3/library/functions.html#int) or [float](https://docs.python.org/3/library/functions.html#float)): Minimum number of samples to split a node.
* **min_samples_leaf** ([int](https://docs.python.org/3/library/functions.html#int) or [float](https://docs.python.org/3/library/functions.html#float)): Minimum number of samples in each cluster.
* **min_weight_fraction_leaf** ([float](https://docs.python.org/3/library/functions.html#float)): Minimum fraction of the total sample weight in each cluster.
* **max_features** (([int](https://docs.python.org/3/library/functions.html#int), [float](https://docs.python.org/3/library/functions.html#float), {sqrt, log2} or None)): Number of candidate groups tried at each node (see the tree).
* **min_impurity_decrease** ([float](https://docs.python.org/3/library/functions.html#float)): A node is split only if the weighted decrease of the within-cluster
  variance reaches this.
* **n\_components** (([int](https://docs.python.org/3/library/functions.html#int), [float](https://docs.python.org/3/library/functions.html#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. `None`
  keeps every standardized feature.
* **max_relationship_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum number of relationship hops of a path, in the questions and in
  the features that describe the samples.
* **max_lookup_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum number of lookups (many-to-one steps after the last table of a path,
  not counted by `max_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 as
  `mean(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](https://docs.python.org/3/library/functions.html#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](https://docs.python.org/3/library/functions.html#int)): Thresholds per base feature.
* **max_condition_bins** ([int](https://docs.python.org/3/library/functions.html#int)): Candidate cuts per numeric condition column before refinement.
* **max_categories** ([int](https://docs.python.org/3/library/functions.html#int)): Most frequent categories tried in conditions, and that get their own
  features in the description of the samples.
* **record_candidates** ([int](https://docs.python.org/3/library/functions.html#int)): Number of best questions kept for each split node (see the tree).
* **allow_reverse_paths** ([bool](https://docs.python.org/3/library/functions.html#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](https://docs.python.org/3/library/functions.html#int), RandomState or None)): Controls the sampling of `max_features`.

**Attributes:**

* **labels\_** (ndarray of shape (n_samples,)): Cluster of every row of `X` seen in `fit`.
* **n\_clusters\_** ([int](https://docs.python.org/3/library/functions.html#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](https://docs.python.org/3/library/functions.html#float)): Weighted sum of squared distances of the training rows to the centroid
  of their cluster. It is comparable with the `inertia_` of
  [`RelationalKMeans`](#sklink.cluster.RelationalKMeans) when both describe the
  samples with the same features: same `primitives`,
  `max_relationship_depth`, `max_lookup_depth`, `max_categories`
  (whose default differs, 32 here and 10 there) and `n_components`,
  with `conditional` (`False`, as here), `windows`, `include` and
  `exclude` of the k-means left at their defaults.
* **leaf_to_cluster\_** (ndarray of shape (node_count,)): Cluster of every node of `tree_`, `-1` for split nodes. Clusters
  are numbered in the order in which
  [`export_text`](./sklink.inspection#sklink.inspection.export_text) prints their leaves.
* **tree\_** (RelationalTree): Fitted tree structure; `value` holds the centroids.
* **expressions\_** (tuple of Expression): Questions used by the tree.
* **featurizer\_** ([RelationalFeaturizer](./sklink.feature_extraction#sklink.feature_extraction.RelationalFeaturizer)): Fitted featurizer that describes the samples.
* **embedding_feature_names\_** (ndarray of str): Names of the columns of `cluster_centers_` (see
  [`RelationalKMeans`](#sklink.cluster.RelationalKMeans)).
* **feature_importances\_** (ndarray of shape (n_features_in\_,)): Impurity-based importance per column of `X`.
* **expression_importances\_** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Importance per canonical expression name.
* [**schema\_**](#sklink.cluster.RelationalClusteringTree.schema_) ([Schema](./sklink.database#sklink.database.Schema) or None): Part of the database schema the model reads.
* **visibility\_** (Visibility): Visibility rules used during fit.
* **n\_features_in\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of columns of `X`.
* **feature_names_in\_** (ndarray of shape (n_features_in\_,)): Column names of `X` when it has them.

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.

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`](#sklink.cluster.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.

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:**

```pycon
>>> 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_
3
```

**Functions:**

* [**apply**](#sklink.cluster.RelationalClusteringTree.apply): Index of the leaf that each sample ends up in.
* [**decision_path**](#sklink.cluster.RelationalClusteringTree.decision_path): Nodes that each sample goes through.
* [**fit**](#sklink.cluster.RelationalClusteringTree.fit): Grow the clustering tree.
* [**get_depth**](#sklink.cluster.RelationalClusteringTree.get_depth): Depth of the tree (a single leaf has depth 0).
* [**get_n_leaves**](#sklink.cluster.RelationalClusteringTree.get_n_leaves): Return the number of leaves of the tree.
* [**predict**](#sklink.cluster.RelationalClusteringTree.predict): Cluster of every row of `X`: the leaf it reaches.

### `sklink.cluster.RelationalClusteringTree.allow_reverse_paths` {#sklink.cluster.RelationalClusteringTree.allow_reverse_paths}

```python
allow_reverse_paths = allow_reverse_paths
```

### `sklink.cluster.RelationalClusteringTree.apply` {#sklink.cluster.RelationalClusteringTree.apply}

```python
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 in `fit`.

**Returns:**

* **X\_leaves** (ndarray of shape (n_samples,)): Node index of the leaf of each sample.

### `sklink.cluster.RelationalClusteringTree.condition_penalty` {#sklink.cluster.RelationalClusteringTree.condition_penalty}

```python
condition_penalty = condition_penalty
```

### `sklink.cluster.RelationalClusteringTree.criterion` {#sklink.cluster.RelationalClusteringTree.criterion}

```python
criterion: str
```

Split criterion of the tree machinery (fixed).

### `sklink.cluster.RelationalClusteringTree.database` {#sklink.cluster.RelationalClusteringTree.database}

```python
database = database
```

### `sklink.cluster.RelationalClusteringTree.decision_path` {#sklink.cluster.RelationalClusteringTree.decision_path}

```python
decision_path(X: Any) -> scipy.sparse.csr_array
```

Nodes that each sample goes through.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as in `fit`.

**Returns:**

* **indicator** (sparse array of shape (n_samples, n_nodes)): Nonzero entries mark the visited nodes.

### `sklink.cluster.RelationalClusteringTree.entity` {#sklink.cluster.RelationalClusteringTree.entity}

```python
entity = entity
```

### `sklink.cluster.RelationalClusteringTree.fit` {#sklink.cluster.RelationalClusteringTree.fit}

```python
fit(X: Any, y: Any = None, sample_weight: Any = None) -> Self
```

Grow 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`](./sklink.tree#sklink.tree.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 in `X`, but still gets a label.

**Returns:**

* **self** ([RelationalClusteringTree](#sklink.cluster.RelationalClusteringTree)): Fitted estimator.

### `sklink.cluster.RelationalClusteringTree.get_depth` {#sklink.cluster.RelationalClusteringTree.get_depth}

```python
get_depth() -> int
```

Depth of the tree (a single leaf has depth 0).

**Returns:**

* **depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum distance between the root and a leaf.

### `sklink.cluster.RelationalClusteringTree.get_n_leaves` {#sklink.cluster.RelationalClusteringTree.get_n_leaves}

```python
get_n_leaves() -> int
```

Return the number of leaves of the tree.

**Returns:**

* **n\_leaves** ([int](https://docs.python.org/3/library/functions.html#int)): Number of leaves.

### `sklink.cluster.RelationalClusteringTree.handle_unknown_entity` {#sklink.cluster.RelationalClusteringTree.handle_unknown_entity}

```python
handle_unknown_entity = handle_unknown_entity
```

### `sklink.cluster.RelationalClusteringTree.key` {#sklink.cluster.RelationalClusteringTree.key}

```python
key = key
```

### `sklink.cluster.RelationalClusteringTree.max_bins` {#sklink.cluster.RelationalClusteringTree.max_bins}

```python
max_bins = max_bins
```

### `sklink.cluster.RelationalClusteringTree.max_categories` {#sklink.cluster.RelationalClusteringTree.max_categories}

```python
max_categories = max_categories
```

### `sklink.cluster.RelationalClusteringTree.max_condition_bins` {#sklink.cluster.RelationalClusteringTree.max_condition_bins}

```python
max_condition_bins = max_condition_bins
```

### `sklink.cluster.RelationalClusteringTree.max_conditions` {#sklink.cluster.RelationalClusteringTree.max_conditions}

```python
max_conditions = max_conditions
```

### `sklink.cluster.RelationalClusteringTree.max_depth` {#sklink.cluster.RelationalClusteringTree.max_depth}

```python
max_depth = max_depth
```

### `sklink.cluster.RelationalClusteringTree.max_features` {#sklink.cluster.RelationalClusteringTree.max_features}

```python
max_features = max_features
```

### `sklink.cluster.RelationalClusteringTree.max_leaf_nodes` {#sklink.cluster.RelationalClusteringTree.max_leaf_nodes}

```python
max_leaf_nodes: int
```

Leaves of the best-first growth, as the tree machinery checks them.

`n_clusters=1` is applied in `fit`.

### `sklink.cluster.RelationalClusteringTree.max_lookup_depth` {#sklink.cluster.RelationalClusteringTree.max_lookup_depth}

```python
max_lookup_depth = max_lookup_depth
```

### `sklink.cluster.RelationalClusteringTree.max_relationship_depth` {#sklink.cluster.RelationalClusteringTree.max_relationship_depth}

```python
max_relationship_depth = max_relationship_depth
```

### `sklink.cluster.RelationalClusteringTree.max_search_samples` {#sklink.cluster.RelationalClusteringTree.max_search_samples}

```python
max_search_samples = max_search_samples
```

### `sklink.cluster.RelationalClusteringTree.min_impurity_decrease` {#sklink.cluster.RelationalClusteringTree.min_impurity_decrease}

```python
min_impurity_decrease = min_impurity_decrease
```

### `sklink.cluster.RelationalClusteringTree.min_samples_leaf` {#sklink.cluster.RelationalClusteringTree.min_samples_leaf}

```python
min_samples_leaf = min_samples_leaf
```

### `sklink.cluster.RelationalClusteringTree.min_samples_split` {#sklink.cluster.RelationalClusteringTree.min_samples_split}

```python
min_samples_split = min_samples_split
```

### `sklink.cluster.RelationalClusteringTree.min_weight_fraction_leaf` {#sklink.cluster.RelationalClusteringTree.min_weight_fraction_leaf}

```python
min_weight_fraction_leaf = min_weight_fraction_leaf
```

### `sklink.cluster.RelationalClusteringTree.n_clusters` {#sklink.cluster.RelationalClusteringTree.n_clusters}

```python
n_clusters = n_clusters
```

### `sklink.cluster.RelationalClusteringTree.n_components` {#sklink.cluster.RelationalClusteringTree.n_components}

```python
n_components = n_components
```

### `sklink.cluster.RelationalClusteringTree.predict` {#sklink.cluster.RelationalClusteringTree.predict}

```python
predict(X: Any) -> np.ndarray
```

Cluster 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 in `fit`.

**Returns:**

* **labels** (ndarray of shape (n_samples,)): Cluster index of every row.

### `sklink.cluster.RelationalClusteringTree.primitives` {#sklink.cluster.RelationalClusteringTree.primitives}

```python
primitives = primitives
```

### `sklink.cluster.RelationalClusteringTree.random_state` {#sklink.cluster.RelationalClusteringTree.random_state}

```python
random_state = random_state
```

### `sklink.cluster.RelationalClusteringTree.record_candidates` {#sklink.cluster.RelationalClusteringTree.record_candidates}

```python
record_candidates = record_candidates
```

### `sklink.cluster.RelationalClusteringTree.schema_` {#sklink.cluster.RelationalClusteringTree.schema\_}

```python
schema_: Schema | None
```

### `sklink.cluster.RelationalClusteringTree.time` {#sklink.cluster.RelationalClusteringTree.time}

```python
time = time
```

## `sklink.cluster.RelationalKMeans` {#sklink.cluster.RelationalKMeans}

```python
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) -> None
```

Bases: [ClassNamePrefixFeaturesOutMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.ClassNamePrefixFeaturesOutMixin.html), [ClusterMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.ClusterMixin.html), [TransformerMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.TransformerMixin.html), VersionedStateMixin, [BaseEstimator](https://scikit-learn.org/stable/modules/generated/sklearn.base.BaseEstimator.html)

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`](./sklink.feature_extraction#sklink.feature_extraction.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`](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html). 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](../tutorials/clustering)

**Parameters:**

* **database** ([Database](./sklink.database#sklink.database.Database)): Related tables. `None` clusters the columns of `X` alone.
* **entity** ([str](https://docs.python.org/3/library/stdtypes.html#str)): Table whose rows are the samples; required with a database.
* **key** (([str](https://docs.python.org/3/library/stdtypes.html#str), [int](https://docs.python.org/3/library/functions.html#int) or sequence)): Column(s) of `X` holding the entity key.
* **time** ([str](https://docs.python.org/3/library/stdtypes.html#str) or [int](https://docs.python.org/3/library/functions.html#int)): Column of `X` with the cutoff of each sample; `None` is static.
  With a cutoff, a sample is described only by rows before it.
* **n\_clusters** ([int](https://docs.python.org/3/library/functions.html#int)): Number of clusters.
* **init** (('k-means++', random)): Initialization of the centers, in the space of the embedding (see
  [`sklearn.cluster.KMeans`](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html)).
* **n\_init** (auto or [int](https://docs.python.org/3/library/functions.html#int)): Number of runs with different initial centers; the best is kept.
* **max_iter** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum number of iterations of a run.
* **tol** ([float](https://docs.python.org/3/library/functions.html#float)): Relative tolerance on the change of the centers to declare convergence.
* **algorithm** ((lloyd, elkan)): K-means algorithm.
* **n\_components** (([int](https://docs.python.org/3/library/functions.html#int), [float](https://docs.python.org/3/library/functions.html#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. `None`
  keeps every standardized feature.
* **max_relationship_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum number of relationships followed from the entity table.
* **max_lookup_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum number of lookups (many-to-one steps after the last table of a path,
  not counted by `max_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 as
  `mean(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](https://docs.python.org/3/library/functions.html#bool)): Also aggregate numeric columns over the rows of each frequent
  category, as [`RelationalFeaturizer`](./sklink.feature_extraction#sklink.feature_extraction.RelationalFeaturizer)
  does 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](https://docs.python.org/3/library/functions.html#int)): Number of most frequent categories per categorical column that get their
  own `count` and `proportion` features.
* **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](https://docs.python.org/3/library/functions.html#bool)): Allow paths that read rows of other entities through shared tables.
* **handle_unknown_entity** ((error, empty)): What to do with keys of `X` missing from the entity table.
* **random_state** (([int](https://docs.python.org/3/library/functions.html#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 by
  `embedding_feature_names_`.
* **labels\_** (ndarray of shape (n_samples,)): Cluster of every row of `X` seen in `fit`.
* **inertia\_** ([float](https://docs.python.org/3/library/functions.html#float)): Weighted sum of squared distances of the training rows to their center.
* **n\_iter\_** ([int](https://docs.python.org/3/library/functions.html#int)): Iterations of the best run.
* **featurizer\_** ([RelationalFeaturizer](./sklink.feature_extraction#sklink.feature_extraction.RelationalFeaturizer)): Fitted featurizer that describes the samples.
* **embedding_feature_names\_** (ndarray of str): Names of the columns of `cluster_centers_`: a featurizer column, or
  `"name == label"` for the indicator of a category, when
  `n_components` is `None`; `"pc0"`, `"pc1"`, ... otherwise.
* **explained_variance_ratio\_** (ndarray of shape (n_components,)): Fraction of the variance of each principal component; only with
  `n_components`.
* **expressions\_** (tuple of Expression): Expressions of the featurizer columns.
* **schema\_** ([Schema](./sklink.database#sklink.database.Schema) or None): Part of the database schema the model reads.
* **visibility\_** (Visibility): Visibility rules used during fit.
* **n\_features_in\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of columns of `X`.
* **feature_names_in\_** (ndarray of str): Column names of `X`, when it has them.

sklink.cluster.RelationalClusteringTree : Clusters described by questions
about the related tables, such as `count(orders) > 3`.

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.

G. Anderson and B. Pfahringer, "Clustering relational data based on
randomized propositionalization", *Inductive Logic Programming*, 2007.

**Examples:**

```pycon
>>> 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**](#sklink.cluster.RelationalKMeans.fit): Compute the clusters.
* [**fit_transform**](#sklink.cluster.RelationalKMeans.fit_transform): Fit, then return the distances of every row to every center.
* [**predict**](#sklink.cluster.RelationalKMeans.predict): Closest center of every row of `X`.
* [**score**](#sklink.cluster.RelationalKMeans.score): Opposite of the inertia of `X` with the fitted centers.
* [**transform**](#sklink.cluster.RelationalKMeans.transform): Distances of every row of `X` to every center.

### `sklink.cluster.RelationalKMeans.algorithm` {#sklink.cluster.RelationalKMeans.algorithm}

```python
algorithm = algorithm
```

### `sklink.cluster.RelationalKMeans.allow_reverse_paths` {#sklink.cluster.RelationalKMeans.allow_reverse_paths}

```python
allow_reverse_paths = allow_reverse_paths
```

### `sklink.cluster.RelationalKMeans.conditional` {#sklink.cluster.RelationalKMeans.conditional}

```python
conditional = conditional
```

### `sklink.cluster.RelationalKMeans.database` {#sklink.cluster.RelationalKMeans.database}

```python
database = database
```

### `sklink.cluster.RelationalKMeans.entity` {#sklink.cluster.RelationalKMeans.entity}

```python
entity = entity
```

### `sklink.cluster.RelationalKMeans.exclude` {#sklink.cluster.RelationalKMeans.exclude}

```python
exclude = exclude
```

### `sklink.cluster.RelationalKMeans.fit` {#sklink.cluster.RelationalKMeans.fit}

```python
fit(X: Any, y: Any = None, sample_weight: Any = None) -> Self
```

Compute 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 in `X`, but
  still gets a label.

**Returns:**

* **self** ([RelationalKMeans](#sklink.cluster.RelationalKMeans)): Fitted estimator.

### `sklink.cluster.RelationalKMeans.fit_transform` {#sklink.cluster.RelationalKMeans.fit_transform}

```python
fit_transform(X: Any, y: Any = None, sample_weight: Any = None) -> np.ndarray
```

Fit, 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 (see `fit`).

**Returns:**

* **distances** (ndarray of shape (n_samples, n_clusters)): Euclidean distance to each center in the embedding space.

### `sklink.cluster.RelationalKMeans.handle_unknown_entity` {#sklink.cluster.RelationalKMeans.handle_unknown_entity}

```python
handle_unknown_entity = handle_unknown_entity
```

### `sklink.cluster.RelationalKMeans.include` {#sklink.cluster.RelationalKMeans.include}

```python
include = include
```

### `sklink.cluster.RelationalKMeans.init` {#sklink.cluster.RelationalKMeans.init}

```python
init = init
```

### `sklink.cluster.RelationalKMeans.key` {#sklink.cluster.RelationalKMeans.key}

```python
key = key
```

### `sklink.cluster.RelationalKMeans.max_categories` {#sklink.cluster.RelationalKMeans.max_categories}

```python
max_categories = max_categories
```

### `sklink.cluster.RelationalKMeans.max_iter` {#sklink.cluster.RelationalKMeans.max_iter}

```python
max_iter = max_iter
```

### `sklink.cluster.RelationalKMeans.max_lookup_depth` {#sklink.cluster.RelationalKMeans.max_lookup_depth}

```python
max_lookup_depth = max_lookup_depth
```

### `sklink.cluster.RelationalKMeans.max_relationship_depth` {#sklink.cluster.RelationalKMeans.max_relationship_depth}

```python
max_relationship_depth = max_relationship_depth
```

### `sklink.cluster.RelationalKMeans.n_clusters` {#sklink.cluster.RelationalKMeans.n_clusters}

```python
n_clusters = n_clusters
```

### `sklink.cluster.RelationalKMeans.n_components` {#sklink.cluster.RelationalKMeans.n_components}

```python
n_components = n_components
```

### `sklink.cluster.RelationalKMeans.n_init` {#sklink.cluster.RelationalKMeans.n_init}

```python
n_init = n_init
```

### `sklink.cluster.RelationalKMeans.predict` {#sklink.cluster.RelationalKMeans.predict}

```python
predict(X: Any) -> np.ndarray
```

Closest 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 in `fit`.

**Returns:**

* **labels** (ndarray of shape (n_samples,)): Cluster index of every row.

### `sklink.cluster.RelationalKMeans.primitives` {#sklink.cluster.RelationalKMeans.primitives}

```python
primitives = primitives
```

### `sklink.cluster.RelationalKMeans.random_state` {#sklink.cluster.RelationalKMeans.random_state}

```python
random_state = random_state
```

### `sklink.cluster.RelationalKMeans.score` {#sklink.cluster.RelationalKMeans.score}

```python
score(X: Any, y: Any = None, sample_weight: Any = None) -> float
```

Opposite 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 in `fit`.
* **y** (None): Ignored.
* **sample_weight** (array-like of shape (n_samples,)): Sample weights.

**Returns:**

* **score** ([float](https://docs.python.org/3/library/functions.html#float)): Minus the weighted sum of squared distances to the closest center.

### `sklink.cluster.RelationalKMeans.time` {#sklink.cluster.RelationalKMeans.time}

```python
time = time
```

### `sklink.cluster.RelationalKMeans.tol` {#sklink.cluster.RelationalKMeans.tol}

```python
tol = tol
```

### `sklink.cluster.RelationalKMeans.transform` {#sklink.cluster.RelationalKMeans.transform}

```python
transform(X: Any) -> np.ndarray
```

Distances 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 in `fit`.

**Returns:**

* **distances** (ndarray of shape (n_samples, n_clusters)): Euclidean distance to each center in the embedding space.

### `sklink.cluster.RelationalKMeans.windows` {#sklink.cluster.RelationalKMeans.windows}

```python
windows = windows
```

:::
