> ## Documentation Index
> Fetch the complete documentation index at: https://docs.graphext.com/llms.txt
> Use this file to discover all available pages before exploring further.

# train_clustering

> Train and store a machine learning model to be loaded at a later point for prediction. 

Density-based clustering with ["HDBSCAN"](https://hdbscan.readthedocs.io/en/latest/how_hdbscan_works.html)

Generates a hierarchy of clusters, but then automatically selects the best *flat* clustering based on the stability
of clusters across a range of density thresholds. Roughly speaking, if a cluster's subclusters persists over a larger
range of the density parameter then the parent cluster itself, the subclusters will be selected, otherwise the parent.
The main parameter influencing cluster selection is `min_cluster_size`.

Can be used to predict the clusters of new data without changing the existing clustering.

## Usage

The following example shows how the step can be used in a recipe.

<Accordion title="Examples" icon="code" defaultOpen="true">
  <Tabs>
    <Tab title="Example 1">
      Train an HDBSCAN model with default parameters.

      ```stan theme={null}
      train_clustering(ds) -> (ds.predicted, model)
      ```
    </Tab>

    <Tab title="Signature">
      General syntax for using the step in a recipe. Shows the inputs and outputs the step is expected to receive and will produce respectively. For futher details see sections below.

      ```stan theme={null}
      train_clustering(ds: dataset, {
          "param": value,
          ...
      }) -> (predicted: category, model: model_clustering[ds])
      ```
    </Tab>
  </Tabs>
</Accordion>

## Inputs & Outputs

The following are the inputs expected by the step and the outputs it produces. These are generally
columns (`ds.first_name`), datasets (`ds` or `ds[["first_name", "last_name"]]`) or models (referenced
by name e.g. `"churn-clf"`).

<Accordion title="Inputs" icon="right-to-bracket">
  <ParamField path="ds" type="dataset" required>
    Should contain the target column and the feature columns you wish to use in the model.
  </ParamField>
</Accordion>

<Accordion title="Outputs" icon="right-from-bracket">
  <ParamField path="predicted" type="column[category]" required>
    Column containing results of the model.
  </ParamField>

  <ParamField path="model" type="file[model_clustering[ds]]" required>
    Zip file containing the trained model and associated information.
  </ParamField>

  <ParamField path="info" type="file.hidden" required />
</Accordion>

## Configuration

The following parameters can be used to configure the behaviour of the step by including them in
a json object as the last "input" to the step, i.e. `step(..., {"param": "value", ...}) -> (output)`.

<Accordion title="Parameters" defaultOpen="true" icon="sliders">
  <ParamField path="encode_features" type="boolean" default="true">
    Toggle encoding of feature columns.
    When enabled, Graphext will auto-convert any column types to the numeric type before
    fitting the model. How this conversion is done can be configured using the `feature_encoder`
    option below.

    <Warning>If disabled, any model trained in this step will assume that input data
    is already in an appropriate format (e.g. numerical and not containing any missing values).</Warning>
  </ParamField>

  <ParamField path="feature_encoder" type="[null, object]">
    Configures encoding of feature columns.
    By default (`null`), Graphext chooses automatically how to convert any column types the model
    may not understand natively to a numeric type.

    A configuration object can be passed instead to overwrite specific parameter values with respect
    to their default values.

    <Accordion title="Properties">
      <ParamField path="number" type="object">
        Numeric encoder.
        Configures encoding of numeric features.

        <Accordion title="Properties">
          <ParamField path="indicate_missing" type="boolean">
            Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
          </ParamField>

          <ParamField path="imputer" type="[null, string]">
            Whether and how to impute (replace/fill) missing values.

            Values must be one of the following:

            * `Mean`
            * `Median`
            * `MostFrequent`
            * `Const`
            * `None`
          </ParamField>

          <ParamField path="scaler" type="[null, string]">
            Whether and how to scale the final numerical values (across a single column).

            Values must be one of the following:

            * `Standard`
            * `Robust`
            * `KNN`
            * `None`
          </ParamField>

          <ParamField path="scaler_params" type="object">
            Further parameters passed to the `scaler` function.
            Details depend no the particular scaler used.
          </ParamField>
        </Accordion>
      </ParamField>

      <ParamField path="bool" type="object">
        Boolean encoder.
        Configures encoding of boolean features.

        <Accordion title="Properties">
          <ParamField path="indicate_missing" type="boolean">
            Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
          </ParamField>

          <ParamField path="imputer" type="[null, string]">
            Whether and how to impute (replace/fill) missing values.

            Values must be one of the following:

            * `MostFrequent`
            * `Const`
            * `None`
          </ParamField>
        </Accordion>
      </ParamField>

      <ParamField path="ordinal" type="object">
        Ordinal encoder.
        Configures encoding of categorical features that have a natural order.

        <Accordion title="Properties">
          <ParamField path="indicate_missing" type="boolean">
            Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
          </ParamField>

          <ParamField path="imputer" type="[null, string]">
            Whether and how to impute (replace/fill) missing values.

            Values must be one of the following:

            * `MostFrequent`
            * `Const`
            * `None`
          </ParamField>
        </Accordion>
      </ParamField>

      <ParamField path="category" type="[object, object]">
        Category encoder.
        May contain either a single configuration for all categorical variables, or two different configurations
        for low- and high-cardinality variables. For further details pick one of the two options below.

        <Accordion title="Options">
          <Tabs>
            <Tab title="Simple category encoder">
              <ParamField path="indicate_missing" type="boolean">
                Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
              </ParamField>

              <ParamField path="imputer" type="[null, string]">
                Whether and how to impute (replace/fill) missing values.

                Values must be one of the following:

                * `MostFrequent`
                * `Const`
                * `None`
              </ParamField>

              <ParamField path="max_categories" type="[null, integer]">
                Maximum number of unique categories to encode.
                Only the N-1 most common categories will be encoded, and the rest will be grouped into a single
                "Others" category.

                Values must be in the following range:

                ```javascript theme={null}
                1 ≤ max_categories < inf
                ```
              </ParamField>

              <ParamField path="encoder" type="[null, string]">
                How to encode categories.

                Values must be one of the following:

                `OneHot` `Label` `Ordinal` `Binary` `Frequency` `None`
              </ParamField>

              <ParamField path="scaler" type="[null, string]">
                Whether and how to scale the final numerical values (across a single column).

                Values must be one of the following:

                * `Standard`
                * `Robust`
                * `KNN`
                * `None`
              </ParamField>
            </Tab>

            <Tab title="Conditional category encoder">
              <ParamField path="cardinality_treshold" type="integer">
                Condition for application of low- or high-cardinality configuration.
                Number of unique categories below which the `low_cardinality` configuration is used,
                and above which the `high_cardinality` configuration is used.

                Values must be in the following range:

                ```javascript theme={null}
                3 ≤ cardinality_treshold < inf
                ```
              </ParamField>

              <ParamField path="low_cardinality" type="object">
                Low cardinality configuration.
                Used for categories with fewer than `cardinality_threshold` unique categories.

                <Accordion title="Properties">
                  <ParamField path="indicate_missing" type="boolean">
                    Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
                  </ParamField>

                  <ParamField path="imputer" type="[null, string]">
                    Whether and how to impute (replace/fill) missing values.

                    Values must be one of the following:

                    * `MostFrequent`
                    * `Const`
                    * `None`
                  </ParamField>

                  <ParamField path="max_categories" type="[null, integer]">
                    Maximum number of unique categories to encode.
                    Only the N-1 most common categories will be encoded, and the rest will be grouped into a single
                    "Others" category.

                    Values must be in the following range:

                    ```javascript theme={null}
                    1 ≤ max_categories < inf
                    ```
                  </ParamField>

                  <ParamField path="encoder" type="[null, string]">
                    How to encode categories.

                    Values must be one of the following:

                    `OneHot` `Label` `Ordinal` `Binary` `Frequency` `None`
                  </ParamField>

                  <ParamField path="scaler" type="[null, string]">
                    Whether and how to scale the final numerical values (across a single column).

                    Values must be one of the following:

                    * `Standard`
                    * `Robust`
                    * `KNN`
                    * `None`
                  </ParamField>
                </Accordion>
              </ParamField>

              <ParamField path="high_cardinality" type="object">
                High cardinality configuration.
                Used for categories with more than `cardinality_threshold` unique categories.

                <Accordion title="Properties">
                  <ParamField path="indicate_missing" type="boolean">
                    Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
                  </ParamField>

                  <ParamField path="imputer" type="[null, string]">
                    Whether and how to impute (replace/fill) missing values.

                    Values must be one of the following:

                    * `MostFrequent`
                    * `Const`
                    * `None`
                  </ParamField>

                  <ParamField path="max_categories" type="[null, integer]">
                    Maximum number of unique categories to encode.
                    Only the N-1 most common categories will be encoded, and the rest will be grouped into a single
                    "Others" category.

                    Values must be in the following range:

                    ```javascript theme={null}
                    1 ≤ max_categories < inf
                    ```
                  </ParamField>

                  <ParamField path="encoder" type="[null, string]">
                    How to encode categories.

                    Values must be one of the following:

                    `OneHot` `Label` `Ordinal` `Binary` `Frequency` `None`
                  </ParamField>

                  <ParamField path="scaler" type="[null, string]">
                    Whether and how to scale the final numerical values (across a single column).

                    Values must be one of the following:

                    * `Standard`
                    * `Robust`
                    * `KNN`
                    * `None`
                  </ParamField>
                </Accordion>
              </ParamField>
            </Tab>
          </Tabs>
        </Accordion>
      </ParamField>

      <ParamField path="multilabel" type="[object, object]">
        Multilabel encoder.
        Configures encoding of multivalued categorical features (variable length lists of categories,
        or the semantic type `list[category]` for short). May contain either a single configuration for
        all multilabel variables, or two different configurations for low- and high-cardinality variables.
        For further details pick one of the two options below.

        <Accordion title="Options">
          <Tabs>
            <Tab title="Simple multilabel encoder">
              <ParamField path="indicate_missing" type="boolean">
                Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
              </ParamField>

              <ParamField path="encoder" type="[null, string]">
                How to encode categories/labels in multilabel (list\[category]) columns.

                Values must be one of the following:

                * `Binarizer`
                * `TfIdf`
                * `None`
              </ParamField>

              <ParamField path="max_categories" type="[null, integer]">
                Maximum number of categories/labels to encode.
                If a number is provided, the result of the encoding will be reduced to these many dimensions (columns)
                using scikit-learn's [truncated SVD](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html).
                When applied together with (after a) Tf-Idf encoding, this performs a kind of
                [latent semantic analysis](https://en.wikipedia.org/wiki/Latent_semantic_analysis).

                Values must be in the following range:

                ```javascript theme={null}
                2 ≤ max_categories < inf
                ```
              </ParamField>

              <ParamField path="scaler" type="[null, string]">
                How to scale the encoded (numerical columns).

                Values must be one of the following:

                * `Euclidean`
                * `KNN`
                * `Norm`
                * `None`
              </ParamField>
            </Tab>

            <Tab title="Conditional multilabel encoder">
              <ParamField path="cardinality_treshold" type="integer">
                Condition for application of low- or high-cardinality configuration.
                Number of unique categories below which the `low_cardinality` configuration is used,
                and above which the `high_cardinality` configuration is used.

                Values must be in the following range:

                ```javascript theme={null}
                3 ≤ cardinality_treshold < inf
                ```
              </ParamField>

              <ParamField path="low_cardinality" type="object">
                Low cardinality configuration.
                Used for mulitabel columns with fewer than `cardinality_threshold` unique categories/labels.

                <Accordion title="Properties">
                  <ParamField path="indicate_missing" type="boolean">
                    Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
                  </ParamField>

                  <ParamField path="encoder" type="[null, string]">
                    How to encode categories/labels in multilabel (list\[category]) columns.

                    Values must be one of the following:

                    * `Binarizer`
                    * `TfIdf`
                    * `None`
                  </ParamField>

                  <ParamField path="max_categories" type="[null, integer]">
                    Maximum number of categories/labels to encode.
                    If a number is provided, the result of the encoding will be reduced to these many dimensions (columns)
                    using scikit-learn's [truncated SVD](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html).
                    When applied together with (after a) Tf-Idf encoding, this performs a kind of
                    [latent semantic analysis](https://en.wikipedia.org/wiki/Latent_semantic_analysis).

                    Values must be in the following range:

                    ```javascript theme={null}
                    2 ≤ max_categories < inf
                    ```
                  </ParamField>

                  <ParamField path="scaler" type="[null, string]">
                    How to scale the encoded (numerical columns).

                    Values must be one of the following:

                    * `Euclidean`
                    * `KNN`
                    * `Norm`
                    * `None`
                  </ParamField>
                </Accordion>
              </ParamField>

              <ParamField path="high_cardinality" type="object">
                High cardinality configuration.
                Used for categories with more than `cardinality_threshold` unique categories.

                <Accordion title="Properties">
                  <ParamField path="indicate_missing" type="boolean">
                    Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
                  </ParamField>

                  <ParamField path="encoder" type="[null, string]">
                    How to encode categories/labels in multilabel (list\[category]) columns.

                    Values must be one of the following:

                    * `Binarizer`
                    * `TfIdf`
                    * `None`
                  </ParamField>

                  <ParamField path="max_categories" type="[null, integer]">
                    Maximum number of categories/labels to encode.
                    If a number is provided, the result of the encoding will be reduced to these many dimensions (columns)
                    using scikit-learn's [truncated SVD](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html).
                    When applied together with (after a) Tf-Idf encoding, this performs a kind of
                    [latent semantic analysis](https://en.wikipedia.org/wiki/Latent_semantic_analysis).

                    Values must be in the following range:

                    ```javascript theme={null}
                    2 ≤ max_categories < inf
                    ```
                  </ParamField>

                  <ParamField path="scaler" type="[null, string]">
                    How to scale the encoded (numerical columns).

                    Values must be one of the following:

                    * `Euclidean`
                    * `KNN`
                    * `Norm`
                    * `None`
                  </ParamField>
                </Accordion>
              </ParamField>
            </Tab>
          </Tabs>
        </Accordion>
      </ParamField>

      <ParamField path="datetime" type="object">
        Datetime encoder.
        Configures encoding of datetime (timestamp) features.

        <Accordion title="Properties">
          <ParamField path="indicate_missing" type="boolean">
            Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
          </ParamField>

          <ParamField path="components" type="array[string]">
            A list of numerical components to extract.
            Will create one numeric column for each component.

            <Accordion title="Array items">
              <ParamField path="Item" type="string">
                Each item in array.

                Values must be one of the following:

                `day` `dayofweek` `dayofyear` `hour` `minute` `month` `quarter` `season` `second` `week` `weekday` `weekofyear` `year`
              </ParamField>
            </Accordion>
          </ParamField>

          <ParamField path="cycles" type="array[string]">
            A list of cyclical time features to extract.
            "Cycles" are numerical transformations of features that should be represented on a circle. E.g. months,
            ranging from 1 to 12, should be arranged such that 12 and 1 are next to each other, rather than on
            opposite ends of a linear scale. We represent such cyclical time features on a circle by creating two
            columns for each original feature: the sin and cos of the numerical feature after appropriate scaling.

            <Accordion title="Array items">
              <ParamField path="Item" type="string">
                Each item in array.

                Values must be one of the following:

                * `day`
                * `dayofweek`
                * `dayofyear`
                * `hour`
                * `month`
              </ParamField>
            </Accordion>
          </ParamField>

          <ParamField path="epoch" type="[null, boolean]">
            Whether to include the epoch as new feature (seconds since 01/01/1970).
          </ParamField>

          <ParamField path="imputer" type="[null, string]">
            Whether and how to impute (replace/fill) missing values.

            Values must be one of the following:

            * `Mean`
            * `Median`
            * `MostFrequent`
            * `Const`
            * `None`
          </ParamField>

          <ParamField path="component_scaler" type="[null, string]">
            Whether and how to scale the final numerical values (across a single column).

            Values must be one of the following:

            * `Standard`
            * `Robust`
            * `KNN`
            * `None`
          </ParamField>

          <ParamField path="vector_scaler" type="[null, string]">
            How to scale the encoded (numerical columns).

            Values must be one of the following:

            * `Euclidean`
            * `KNN`
            * `Norm`
            * `None`
          </ParamField>
        </Accordion>
      </ParamField>

      <ParamField path="embedding" type="object">
        Embedding/vector encoder.
        Configures encoding of multivalued numerical features (variable length lists of numbers, i.e. vectors, or the semantic type `list[number]` for short).

        <Accordion title="Properties">
          <ParamField path="indicate_missing" type="boolean">
            Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
          </ParamField>

          <ParamField path="scaler" type="[null, string]">
            How to scale the encoded (numerical columns).

            Values must be one of the following:

            * `Euclidean`
            * `KNN`
            * `Norm`
            * `None`
          </ParamField>
        </Accordion>
      </ParamField>

      <ParamField path="text" type="object">
        Text encoder.
        Configures encoding of text (natural language) features. Currently only allows
        [Tf-Idf](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) embeddings to represent texts. If you wish
        to use other embeddings, e.g. semantic, Word2Vec etc., transform your text column first using
        another step, and then use that result instead of the original texts.

        <Warning>Texts are *excluded* by default from the overall encoding of the dataset. See parameter
        `include_text_features` below to active it.</Warning>

        <Accordion title="Properties">
          <ParamField path="indicate_missing" type="boolean">
            Toggle the addition of a column using 0s and 1s to indicate where an input column contained missing values.
          </ParamField>

          <ParamField path="encoder_params" type="object">
            Parameters to be passed to the text encoder (Tf-Idf parameters only for now).
            See [scikit-learn's documentation](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html)
            for detailed parameters and their explanation.
          </ParamField>

          <ParamField path="n_components" type="integer">
            How many output features to generate.
            The resulting Tf-Idf vectors will be reduced to these many dimensions (columns) using scikit-learn's
            [truncated SVD](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html).
            This performs a kind of [latent semantic analysis](https://en.wikipedia.org/wiki/Latent_semantic_analysis).
            By default we will reduce to 200 components.

            Values must be in the following range:

            ```javascript theme={null}
            2 ≤ n_components ≤ 1024
            ```
          </ParamField>

          <ParamField path="scaler" type="[null, string]">
            How to scale the encoded (numerical columns).

            Values must be one of the following:

            * `Euclidean`
            * `KNN`
            * `Norm`
            * `None`
          </ParamField>
        </Accordion>
      </ParamField>
    </Accordion>
  </ParamField>

  <ParamField path="include_text_features" type="boolean" default="false">
    Whether to include or ignore text columns during the processing of input data.
    Enabling this will convert texts to their TfIdf representation. Each text will be
    converted to an N-dimensional vector in which each component measures the relative
    "over-representation" of a specific word (or n-gram) relative to its overall
    frequency in the whole dataset. This is disabled by default because it will
    often be better to convert texts explicitly using a previous step, such as
    `embed_text` or `embed_text_with_model`.
  </ParamField>

  <ParamField path="params" type="object">
    Model parameters.
    Also see [official HDBSCAN documentation](https://hdbscan.readthedocs.io/en/latest/parameter_selection.html) for details.

    <Accordion title="Properties">
      <ParamField path="min_cluster_size" type="integer" default="50">
        The minimum size of clusters.
        Intuitively, the smallest size grouping you wish to consider a cluster. When selecting a flat clustering from the cluster
        hierarchy, splits that contain fewer points than this will be considered points "falling out" of a cluster rather than a
        cluster splitting into two new clusters.

        Values must be in the following range:

        ```javascript theme={null}
        1 ≤ min_cluster_size < inf
        ```
      </ParamField>

      <ParamField path="min_samples" type="integer" default="5">
        Determines how conservative the clustering is.
        The larger the value, the more points will be declared as noise, and clusters will be restricted to progressively
        more dense areas.

        Values must be in the following range:

        ```javascript theme={null}
        1 ≤ min_samples < inf
        ```
      </ParamField>

      <ParamField path="cluster_selection_epsilon" type="number" default="0.0">
        Distance threshold.
        Clusters below this value will be merged. If default parameters result in areas with a large number of micro-clusters,
        this parameter can help merging these clusters together. For example, set the value to 0.5 if you don't want to separate
        clusters that are less than 0.5 units apart (the distance distribution depends on your specific data).

        Values must be in the following range:

        ```javascript theme={null}
        0.0 ≤ cluster_selection_epsilon < inf
        ```
      </ParamField>

      <ParamField path="cluster_selection_method" type="string" default="eof">
        Method used to select clusters from the cluster hierarchy.
        The default, "excess of mass" (`eom`), can sometimes pick one or two large clusters and then a number
        of small extra clusters. If you're interested in a more fine-grained clustering with a larger number of more homogeously
        sized clusters, you may prefer selecting leaf clustering (`leaf`).

        Values must be one of the following:

        * `eof`
        * `leaf`
      </ParamField>
    </Accordion>
  </ParamField>

  <ParamField path="seed" type="integer">
    Seed for random number generator ensuring reproducibility.

    Values must be in the following range:

    ```javascript theme={null}
    0 ≤ seed < inf
    ```
  </ParamField>
</Accordion>
