.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/pipeline_lisn_lsa_umap_hdbscan_hierarchical.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_auto_examples_pipeline_lisn_lsa_umap_hdbscan_hierarchical.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_auto_examples_pipeline_lisn_lsa_umap_hdbscan_hierarchical.py:


Processing LISN data with Pipeline API (LSA projection)
====================================================================

In this example we will process LISN (Laboratoire Interdisciplinaire des Sciences du Numérique) dataset using `Pipeline` API. LISN dataset contains all articles from HAL (https://hal.archives-ouvertes.fr/) published by authors from LISN between 2000-2022.

The pipeline will comprise of the following steps:

- extract entities (articles, authors, teams, labs, words) from a collection of
  scientific articles
- use Latent Semantic Analysis (LSA) to generate n-dimensional vector 
  representation of the entities
- use Uniform Manifold Approximation and Projection (UMAP) to project those 
  entities in 2 dimensions
- use HDBScan clustering to cluster entities
- find their nearest neighbors.

.. GENERATED FROM PYTHON SOURCE LINES 21-27

Create LISN Dataset
====================

We will first create Dataset for LISN. 

The CSV file containing the data can be downloaded from https://zenodo.org/record/7323538/files/lisn_2000_2022.csv . We will use version 2.0.0 of the dataset. When we specify the URL to `CSVDataset`, it will download the file if it does not exist locally.

.. GENERATED FROM PYTHON SOURCE LINES 27-41

.. code-block:: Python


    from cartodata.pipeline.datasets import CSVDataset  # noqa
    from pathlib import Path # noqa

    ROOT_DIR = Path.cwd().parent
    # The directory where files necessary to load dataset columns reside
    INPUT_DIR = ROOT_DIR / "datas"
    # The directory where the generated dump files will be saved
    TOP_DIR = ROOT_DIR / "dumps"

    dataset = CSVDataset(name="lisn", input_dir=INPUT_DIR, version="2.0.0", filename="lisn_2000_2022.csv", 
                           fileurl="https://zenodo.org/record/7323538/files/lisn_2000_2022.csv", 
                           columns=None, index_col=0, top_dir=TOP_DIR)








.. GENERATED FROM PYTHON SOURCE LINES 42-45

This will check if the dataset file already exists locally. If it does not, it downloads the file from the specified URL and the loads the file to a pandas Dataframe.

Let's view the dataset.

.. GENERATED FROM PYTHON SOURCE LINES 45-50

.. code-block:: Python


    df = dataset.df

    df.head(5)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    Downloading data from https://zenodo.org/records/7323538/files/lisn_2000_2022.csv (6.3 MB)


    file_sizes:   0%|                                   | 0.00/6.59M [00:00<?, ?B/s]
    file_sizes:  51%|█████████████▎            | 3.37M/6.59M [00:00<00:00, 33.3MB/s]
    file_sizes: 100%|██████████████████████████| 6.59M/6.59M [00:00<00:00, 44.1MB/s]
    Successfully downloaded file to /builds/2mk6rsew/0/hgozukan/cartolabe-data/dumps/lisn/2.0.0/lisn_2000_2022.csv


.. raw:: html

    <div class="output_subarea output_html rendered_html output_result">
    <div>
    <style scoped>
        .dataframe tbody tr th:only-of-type {
            vertical-align: middle;
        }

        .dataframe tbody tr th {
            vertical-align: top;
        }

        .dataframe thead th {
            text-align: right;
        }
    </style>
    <table border="1" class="dataframe">
      <thead>
        <tr style="text-align: right;">
          <th></th>
          <th>structId_i</th>
          <th>authFullName_s</th>
          <th>en_abstract_s</th>
          <th>en_keyword_s</th>
          <th>en_title_s</th>
          <th>structAcronym_s</th>
          <th>producedDateY_i</th>
          <th>producedDateM_i</th>
          <th>halId_s</th>
          <th>docid</th>
          <th>en_domainAllCodeLabel_fs</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>0</th>
          <td>[2544, 92966, 411575, 441569]</td>
          <td>Frédéric Blanqui</td>
          <td>In the last twenty years, several approaches t...</td>
          <td>Higher-order rewriting,Termination,Confluence</td>
          <td>Termination and Confluence of Higher-Order Rew...</td>
          <td>LRI,UP11,CNRS,LISN</td>
          <td>2000</td>
          <td>7.0</td>
          <td>inria-00105556</td>
          <td>105556</td>
          <td>Logic in Computer Science,Computer Science</td>
        </tr>
        <tr>
          <th>1</th>
          <td>[2544, 92966, 411575, 441569]</td>
          <td>Sébastien Tixeuil</td>
          <td>When a distributed system is subject to transi...</td>
          <td>Self-stabilization,Distributed Systems,Distrib...</td>
          <td>Efficient Self-stabilization</td>
          <td>LRI,UP11,CNRS,LISN</td>
          <td>2000</td>
          <td>1.0</td>
          <td>tel-00124843</td>
          <td>124843</td>
          <td>Networking and Internet Architecture,Computer ...</td>
        </tr>
        <tr>
          <th>2</th>
          <td>[1167, 300340, 301492, 564132, 441569, 2544, 9...</td>
          <td>Michèle Sebag,Céline Rouveirol</td>
          <td>One of the obstacles to widely using first-ord...</td>
          <td>Bounded reasoning,First order logic,Inductive ...</td>
          <td>Resource-bounded relational reasoning: inducti...</td>
          <td>LMS,X,PSL,CNRS,LRI,UP11,CNRS,LISN</td>
          <td>2000</td>
          <td>NaN</td>
          <td>hal-00111312</td>
          <td>2263842</td>
          <td>Mechanics,Engineering Sciences,physics</td>
        </tr>
        <tr>
          <th>3</th>
          <td>[994, 15786, 301340, 303171, 441569, 34499, 81...</td>
          <td>Philippe Balbiani,Jean-François Condotta,Gérar...</td>
          <td>This paper organizes the topologic forms of th...</td>
          <td>Temporal reasoning,Constraint handling,Computa...</td>
          <td>Reasoning about generalized intervals : Horn r...</td>
          <td>LIPN,UP13,USPC,CNRS,IRIT,UT1,UT2J,UT3,CNRS,Tou...</td>
          <td>2000</td>
          <td>NaN</td>
          <td>hal-03300321</td>
          <td>3300321</td>
          <td>Artificial Intelligence,Computer Science</td>
        </tr>
        <tr>
          <th>4</th>
          <td>[1315, 25027, 59704, 564132, 300009, 441569, 4...</td>
          <td>Roberto Di Cosmo,Delia Kesner,Emmanuel Polonovski</td>
          <td>We refine the simulation technique introduced ...</td>
          <td>Linear logic,Proof nets,Lambda-calculus,Explic...</td>
          <td>Proof Nets and Explicit Substitutions</td>
          <td>LIENS,DI-ENS,ENS-PSL,PSL,Inria,CNRS,CNRS,LRI,U...</td>
          <td>2000</td>
          <td>NaN</td>
          <td>hal-00384955</td>
          <td>384955</td>
          <td>Logic in Computer Science,Computer Science</td>
        </tr>
      </tbody>
    </table>
    </div>
    </div>
    <br />
    <br />

.. GENERATED FROM PYTHON SOURCE LINES 51-52

The dataframe that we just read consists of 4262 articles as rows.

.. GENERATED FROM PYTHON SOURCE LINES 52-55

.. code-block:: Python


    df.shape[0]





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    4262



.. GENERATED FROM PYTHON SOURCE LINES 56-57

And their authors, abstract, keywords, title, research labs and domain as columns.

.. GENERATED FROM PYTHON SOURCE LINES 57-60

.. code-block:: Python


    print(*df.columns, sep="\n")





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    structId_i
    authFullName_s
    en_abstract_s
    en_keyword_s
    en_title_s
    structAcronym_s
    producedDateY_i
    producedDateM_i
    halId_s
    docid
    en_domainAllCodeLabel_fs




.. GENERATED FROM PYTHON SOURCE LINES 61-82

Now we should define our entities and set the column names corresponding to those entities from the data file. We have 5 entities:

| entity | column name in the file |
---------|-------------|
| articles | en_title_s |
| authors | authFullName_s |
| teams | structAcronym_s |
| labs | structAcronym_s |
| words | en_abstract_s, en_title_s, en_keyword_s, en_domainAllCodeLabel_fs |


Cartolabe provides 4 types of columns: 


- **IdentityColumn**: The entity of this column represents the main entity of the dataset. The column data corresponding to the entity in the file should contain a single value and this value should be unique among column values. There can only be one `IdentityColumn` in the dataset.
- **CSColumn**: The entity of this column type is related to the main entity, and can contain single or comma separated values.
- **CorpusColumn**: The entity of this column type is the corpus related to the main entity. This can be a combination of multiple columns in the file. It uses a modified version of CountVectorizer(https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer).
- **TfidfCorpusColumn**: The entity of this column type is the corpus related to the main entity. This can be a combination of multiple columns in the file or can contain filepath from which to read the text corpus. It uses TfidfVectorizer (https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html).


In this dataset, **Articles** is our main entity. We will define it as IdentityColumn:

.. GENERATED FROM PYTHON SOURCE LINES 82-87

.. code-block:: Python


    from cartodata.pipeline.columns import IdentityColumn, CSColumn, CorpusColumn  # noqa

    articles_column = IdentityColumn(nature="articles", column_name="en_title_s")








.. GENERATED FROM PYTHON SOURCE LINES 88-89

`authFullName_s` column for entity **authors** in the dataset lists the authors who have authored each article, and has comma separated values. We will define a CSColumn:

.. GENERATED FROM PYTHON SOURCE LINES 89-92

.. code-block:: Python


    authors_column = CSColumn(nature="authors", column_name="authFullName_s", filter_min_score=4)








.. GENERATED FROM PYTHON SOURCE LINES 93-98

Here we have set `filter_min_score=4` to indicate that, while processing data, authors who have authored less than 4 articles will be filtered. When it is not set, the default value is `0`, meaning that entities will not be filtered.

**Teams** and **Labs** entities both use `structAcronym_s` column which also has comma separated values. `structAcronym_s` column contains both teams and labs of the articles. For teams entity we will take only teams and for labs entity we will take only labs.

The file **../datas/inria-teams.csv** contains the list of Inria teams. For teams entity, we will whitelist the values from inria-teams.csv and for labs entity, we will blacklist values from inria-teams.csv.

.. GENERATED FROM PYTHON SOURCE LINES 98-105

.. code-block:: Python


    teams_column = CSColumn(nature="teams", column_name="structAcronym_s", whitelist="inria-teams.csv", 
                            filter_min_score=4)

    labs_column = CSColumn(nature="labs", column_name="structAcronym_s", blacklist="inria-teams.csv", 
                            filter_min_score=4)








.. GENERATED FROM PYTHON SOURCE LINES 106-107

For **words** entity, we are going to use multiple columns to create a text corpus for each article:

.. GENERATED FROM PYTHON SOURCE LINES 107-113

.. code-block:: Python


    words_column = CorpusColumn(nature="words", 
                                column_names=["en_abstract_s", "en_title_s", "en_keyword_s", "en_domainAllCodeLabel_fs"],
                                stopwords="stopwords.txt", nb_grams=4, min_df=10, max_df=0.05,
                                min_word_length=5, normalize=True)








.. GENERATED FROM PYTHON SOURCE LINES 114-115

Now we are going to set the columns of the dataset:

.. GENERATED FROM PYTHON SOURCE LINES 115-118

.. code-block:: Python


    dataset.set_columns([articles_column, authors_column, teams_column, labs_column, words_column])








.. GENERATED FROM PYTHON SOURCE LINES 119-127

We can set the columns in any order that we prefer. We will set the first entity as identity entity and the last entity as the corpus. If we set the entities in a different order, the `Dataset` will put the main entity as first.

The dataset for LISN data is ready. Now we will create and run our pipeline. For this pipeline, we will:

- run LSA projection -> N-dimesional
- run UMAP projection  -> 2D
- cluster entities
- find nearest neighbors

.. GENERATED FROM PYTHON SOURCE LINES 129-131

Create and run pipeline
========================

.. GENERATED FROM PYTHON SOURCE LINES 133-134

We will first create a pipeline with the dataset. We will set `hierarchical_dirs=True` to save each entity generated in a directory named with the parameters of generation and places in a hierarchy.

.. GENERATED FROM PYTHON SOURCE LINES 134-139

.. code-block:: Python


    from cartodata.pipeline.common import Pipeline  # noqa

    pipeline = Pipeline(dataset=dataset, top_dir=TOP_DIR, input_dir=INPUT_DIR, hierarchical_dirs=True)








.. GENERATED FROM PYTHON SOURCE LINES 140-141

The workflow generates the `natures` from dataset columns.

.. GENERATED FROM PYTHON SOURCE LINES 141-144

.. code-block:: Python


    pipeline.natures





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    ['articles', 'authors', 'teams', 'labs', 'words']



.. GENERATED FROM PYTHON SOURCE LINES 145-152

Creating correspondance matrices for each entity type
-------------------------------------------------------------------------------

From this table of articles, we want to extract matrices that will map the
correspondance between these articles and the entities we want to use.

Pipeline has `generate_entity_matrices` function to generate matrices and scores for each entity (nature) specified for the dataset.

.. GENERATED FROM PYTHON SOURCE LINES 152-155

.. code-block:: Python


    matrices, scores = pipeline.generate_entity_matrices(force=True)








.. GENERATED FROM PYTHON SOURCE LINES 156-157

The order of matrices and scores correspond to the order of dataset columns specified.

.. GENERATED FROM PYTHON SOURCE LINES 157-160

.. code-block:: Python


    dataset.natures





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    ['articles', 'authors', 'teams', 'labs', 'words']



.. GENERATED FROM PYTHON SOURCE LINES 161-166

**Articles**

The first matrix in matrices and Series in scores corresponds to **articles**. 

The type for article column is `IdentityColumn`. It generates a matrix that simply maps each article to itself. 

.. GENERATED FROM PYTHON SOURCE LINES 166-170

.. code-block:: Python


    articles_mat = matrices[0]
    articles_mat.shape





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    (4262, 4262)



.. GENERATED FROM PYTHON SOURCE LINES 171-172

Having type `IdentityColumn`, each article will have score 1.

.. GENERATED FROM PYTHON SOURCE LINES 172-179

.. code-block:: Python


    articles_scores = scores[0]
    articles_scores.shape

    ""
    articles_scores.head()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    Termination and Confluence of Higher-Order Rewrite Systems                                    1.0
    Efficient Self-stabilization                                                                  1.0
    Resource-bounded relational reasoning: induction and deduction through stochastic matching    1.0
    Reasoning about generalized intervals : Horn representability and tractability                1.0
    Proof Nets and Explicit Substitutions                                                         1.0
    dtype: float64



.. GENERATED FROM PYTHON SOURCE LINES 180-185

**Authors**

The second matrix in matrices and score in scores correspond to **authors**. 

The type for authors column is `CSColumn`. It generates a sparce matrix where rows correspond to articles and columns corresponds to authors.

.. GENERATED FROM PYTHON SOURCE LINES 185-189

.. code-block:: Python


    authors_mat = matrices[1]
    authors_mat.shape





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    (4262, 694)



.. GENERATED FROM PYTHON SOURCE LINES 190-196

Here we see that after filtering authors which have less than 4 articles, there are 694 distinct authors.

The series, which we named `authors_scores`, contains the list of authors
extracted from the column `authFullName_s` with a score that is equal to the
number of rows (articles) that this value was mapped within the `authors_mat`
matrix.

.. GENERATED FROM PYTHON SOURCE LINES 196-200

.. code-block:: Python


    authors_scores = scores[1]
    authors_scores.head()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    Sébastien Tixeuil       47
    Michèle Sebag          137
    Khaldoun Al Agha        20
    Ralf Treinen             5
    Christine Eisenbeis     27
    dtype: int64



.. GENERATED FROM PYTHON SOURCE LINES 201-204

If we look at the *4th* column of the matrix, which corresponds to the author
**Ralf Treinen**, we can see that it has 5 non-zero rows, each row
indicating which articles he authored.

.. GENERATED FROM PYTHON SOURCE LINES 204-207

.. code-block:: Python


    print(authors_mat[:, 3])





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

      (6, 0)        1
      (21, 0)       1
      (37, 0)       1
      (2729, 0)     1
      (3573, 0)     1




.. GENERATED FROM PYTHON SOURCE LINES 208-213

**Teams**

The third matrix in matrices and score in scores correspond to **teams**. 

The type for teams column is `CSColumn`. It generates a sparce matrix where rows correspond to articles and columns corresponds to teams.

.. GENERATED FROM PYTHON SOURCE LINES 213-217

.. code-block:: Python


    teams_mat = matrices[2]
    teams_mat.shape





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    (4262, 33)



.. GENERATED FROM PYTHON SOURCE LINES 218-224

Here we see that after filtering teams which have less than 4 articles, there are 33 distinct teams.

The series, which we named `teams_scores`, contains the list of teams
extracted from the column `structAcronym_s` with a score that is equal to the
number of rows (articles) that this value was mapped within the `teams_mat`
matrix.

.. GENERATED FROM PYTHON SOURCE LINES 224-228

.. code-block:: Python


    teams_scores = scores[2]
    teams_scores.head()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    TAO        533
    Regal       10
    Parkas      14
    DAHU         7
    GALLIUM     23
    dtype: int64



.. GENERATED FROM PYTHON SOURCE LINES 229-234

**Labs**

The fourth matrix in matrices and score in scores correspond to **labs**. 

The type for labs column is `CSColumn`. It generates a sparce matrix where rows correspond to articles and columns corresponds to labs.

.. GENERATED FROM PYTHON SOURCE LINES 234-238

.. code-block:: Python


    labs_mat = matrices[3]
    labs_mat.shape





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    (4262, 549)



.. GENERATED FROM PYTHON SOURCE LINES 239-245

Here we see that after filtering labs which have less than 4 articles, there are 549 distinct labs.

The series, which we named `labs_scores`, contains the list of labs
extracted from the column `structAcronym_s` with a score that is equal to the
number of rows (articles) that this value was mapped within the `labs_mat`
matrix.

.. GENERATED FROM PYTHON SOURCE LINES 245-249

.. code-block:: Python


    labs_scores = scores[3]
    labs_scores.head()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    LRI      4789
    UP11     6271
    CNRS    10217
    LISN     5203
    X         487
    dtype: int64



.. GENERATED FROM PYTHON SOURCE LINES 250-255

**Words**

The fifth matrix in matrices and score in scores correspond to **words**. 

The type for words column is `CorpusColumn`. It creates a corpus merging multiple text columns in the dataset, and then extracts n-grams from that corpus. Finally it generates a sparce matrix where rows correspond to articles and columns corresponds to n-grams.

.. GENERATED FROM PYTHON SOURCE LINES 255-259

.. code-block:: Python


    words_mat = matrices[4]
    words_mat.shape





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    (4262, 4645)



.. GENERATED FROM PYTHON SOURCE LINES 260-265

Here we see that there are 5226 distinct n-grams.

The series, which we named `words_scores`, contains the list of n-grams
with a score that is equal to the number of rows (articles) that this value 
was mapped within the `words_mat` matrix.

.. GENERATED FROM PYTHON SOURCE LINES 265-269

.. code-block:: Python


    words_scores = scores[4]
    words_scores.head()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    abilities     21
    ability      164
    absence       53
    absolute      19
    abstract     174
    dtype: int64



.. GENERATED FROM PYTHON SOURCE LINES 270-280

Dimension reduction
------------------------------

One way to see the matrices that we created is as coordinates in the space of
all articles. What we want to do is to reduce the dimension of this space to
make it easier to work with and see.

**LSA projection**

We'll start by using the LSA (Latent Semantic Analysis) technique to reduce the number of rows in our data.

.. GENERATED FROM PYTHON SOURCE LINES 280-289

.. code-block:: Python


    from cartodata.pipeline.projectionnd import LSAProjection  # noqa

    num_dim = 80

    lsa_projection = LSAProjection(num_dim)

    pipeline.set_projection_nd(lsa_projection)








.. GENERATED FROM PYTHON SOURCE LINES 290-291

Now we can run LSA projection on the matrices.

.. GENERATED FROM PYTHON SOURCE LINES 291-298

.. code-block:: Python


    matrices_nD = pipeline.do_projection_nD(force=True)

    ""
    for nature, matrix in zip(pipeline.natures, matrices_nD):
        print(f"{nature}  -------------   {matrix.shape}")





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    articles  -------------   (80, 4262)
    authors  -------------   (80, 694)
    teams  -------------   (80, 33)
    labs  -------------   (80, 549)
    words  -------------   (80, 4645)




.. GENERATED FROM PYTHON SOURCE LINES 299-300

We have 80 rows for each entity.

.. GENERATED FROM PYTHON SOURCE LINES 302-312

This makes it easier to work with them for clustering or nearest neighbors
tasks, but we also want to project them on a 2D space to be able to map them.

**UMAP projection**

The `UMAP <https://github.com/lmcinnes/umap>`_ (Uniform Manifold Approximation
and Projection) is a dimension reduction technique that can be used for
visualisation similarly to t-SNE.

We use this algorithm to project our matrices in 2 dimensions.

.. GENERATED FROM PYTHON SOURCE LINES 312-320

.. code-block:: Python


    from cartodata.pipeline.projection2d import UMAPProjection  # noqa


    umap_projection = UMAPProjection(n_neighbors=15, min_dist=0.1)

    pipeline.set_projection_2d(umap_projection)








.. GENERATED FROM PYTHON SOURCE LINES 321-322

Now we can run UMAP projection on the LSA matrices.

.. GENERATED FROM PYTHON SOURCE LINES 322-325

.. code-block:: Python


    matrices_2D = pipeline.do_projection_2D(force=True)








.. GENERATED FROM PYTHON SOURCE LINES 326-328

Now that we have 2D coordinates for our points, we can try to plot them to
get a feel of the data's shape.

.. GENERATED FROM PYTHON SOURCE LINES 328-334

.. code-block:: Python


    labels = tuple(pipeline.natures)
    colors = ['b', 'r', 'c', 'y', 'm']

    fig, ax = pipeline.plot_map(matrices_2D, labels, colors)




.. image-sg:: /auto_examples/images/sphx_glr_pipeline_lisn_lsa_umap_hdbscan_hierarchical_001.png
   :alt: pipeline lisn lsa umap hdbscan hierarchical
   :srcset: /auto_examples/images/sphx_glr_pipeline_lisn_lsa_umap_hdbscan_hierarchical_001.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 335-344

The plot above, as we don't have labels for the points, doesn't make much sense
as is. But we can see that the data shows some clusters which we could try to identify.

Clustering
---------------

In order to identify clusters, we use the HDBScan clustering technique on the
articles. We'll also try to label these clusters by selecting the most
frequent words that appear in each cluster's articles.

.. GENERATED FROM PYTHON SOURCE LINES 344-354

.. code-block:: Python


    from cartodata.pipeline.clustering import HDBSCANClustering  # noqa

    # level of clusters, hl: high level, ml: medium level
    cluster_natures = ["hl_clusters", "ml_clusters"]

    hdbscan_clustering = HDBSCANClustering(n=8, base_factor=3, natures=cluster_natures)

    pipeline.set_clustering(hdbscan_clustering)








.. GENERATED FROM PYTHON SOURCE LINES 355-356

Now we can run clustering on the matrices.

.. GENERATED FROM PYTHON SOURCE LINES 356-360

.. code-block:: Python


    (clus_nD, clus_2D, clus_scores, cluster_labels,
    cluster_eval_pos, cluster_eval_neg) = pipeline.do_clustering()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    Nothing in cache, initial Fitting with min_cluster_size=15 Found 98 clusters in 0.2496061189995089s
    Max Fitting with min_cluster_size=30 Found 53 clusters in 0.11711032799939858s
    Max Fitting with min_cluster_size=60 Found 18 clusters in 0.09962272899974778s
    Max Fitting with min_cluster_size=120 Found 11 clusters in 0.08927081399997405s
    Max Fitting with min_cluster_size=240 Found 4 clusters in 0.08782700699975976s
    Midpoint Fitting with min_cluster_size=180 Found 7 clusters in 0.09113641800013284s
    Midpoint Fitting with min_cluster_size=150 Found 8 clusters in 0.09223331199973472s
    No need Re-Fitting with min_cluster_size=150 
    Clusters cached: [4, 7, 8, 11, 18, 53, 98]
    Nothing in cache, initial Fitting with min_cluster_size=15 Found 98 clusters in 0.10032779599987407s
    Max Fitting with min_cluster_size=30 Found 53 clusters in 0.09995358900050633s
    Max Fitting with min_cluster_size=60 Found 18 clusters in 0.098051748999751s
    Midpoint Fitting with min_cluster_size=45 Found 28 clusters in 0.09810328700041282s
    Midpoint Fitting with min_cluster_size=52 Found 18 clusters in 0.09916086700013693s
    Re-Fitting with min_cluster_size=45 Found 28 clusters in 0.09848179599975992s
    Clusters cached: [18, 18, 28, 53, 98]




.. GENERATED FROM PYTHON SOURCE LINES 361-362

As we have specified two levels of clustering, the returned lists wil have two values.

.. GENERATED FROM PYTHON SOURCE LINES 362-365

.. code-block:: Python


    len(clus_2D)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    2



.. GENERATED FROM PYTHON SOURCE LINES 366-367

We will now display two levels of clusters in separate plots, we will start with high level clusters:

.. GENERATED FROM PYTHON SOURCE LINES 367-376

.. code-block:: Python


    clus_scores_hl = clus_scores[0]
    clus_mat_hl = clus_2D[0]


    fig_hl, ax_hl = pipeline.plot_map(matrices_2D, labels, colors, 
                                      title="LISN Dataset High Level Clusters",
                                      annotations=clus_scores_hl.index, annotation_mat=clus_mat_hl)




.. image-sg:: /auto_examples/images/sphx_glr_pipeline_lisn_lsa_umap_hdbscan_hierarchical_002.png
   :alt: LISN Dataset High Level Clusters
   :srcset: /auto_examples/images/sphx_glr_pipeline_lisn_lsa_umap_hdbscan_hierarchical_002.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 377-381

The 8 high level clusters that we created give us a general idea of what the big
clusters of data contain. 

With medium level clusters we have a finer level of detail:

.. GENERATED FROM PYTHON SOURCE LINES 381-390

.. code-block:: Python


    clus_scores_ml = clus_scores[1]
    clus_mat_ml = clus_2D[1]

    fig_ml, ax_ml = pipeline.plot_map(matrices_2D, labels, colors,
                                      title="LISN Dataset Medium Level Clusters",
                                      annotations=clus_scores_ml.index, annotation_mat=clus_mat_ml,
                                      annotation_color='black')




.. image-sg:: /auto_examples/images/sphx_glr_pipeline_lisn_lsa_umap_hdbscan_hierarchical_003.png
   :alt: LISN Dataset Medium Level Clusters
   :srcset: /auto_examples/images/sphx_glr_pipeline_lisn_lsa_umap_hdbscan_hierarchical_003.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 391-394

We have 24 medium level clusters. We can increase the number of clusters to have even finer details to zoom in and focus on smaller areas. 

Now we will save the plots in the `working_dir` directory.

.. GENERATED FROM PYTHON SOURCE LINES 394-397

.. code-block:: Python


    pipeline.save_plots()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    [(<Figure size 960x640 with 1 Axes>, 'lisn_2.0.0_15d3d1d060e5f28d_lsa_80_True_umap_euclidean_15_0.1_random_1.0_None_None_hdbscan_hl_clusters.png'), (<Figure size 960x640 with 1 Axes>, 'lisn_2.0.0_15d3d1d060e5f28d_lsa_80_True_umap_euclidean_15_0.1_random_1.0_None_None_hdbscan_ml_clusters.png')]



.. GENERATED FROM PYTHON SOURCE LINES 398-399

The plots for 2D map is saved under pipeline 2D directory.

.. GENERATED FROM PYTHON SOURCE LINES 399-403

.. code-block:: Python


    for file in pipeline.get_2D_dir().glob("*.png"):
        print(file)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    /builds/2mk6rsew/0/hgozukan/cartolabe-data/dumps/lisn/2.0.0/mat_articles__authors_4_teams_4_labs_4_words_en_abstract_s_en_title_s_en_keyword_s_en_domainAllCodeLabel_fs_10_0.05_None_None_5_4/lsa_80_True/umap_euclidean_15_0.1_random_1.0_None_None/lisn_2.0.0_15d3d1d060e5f28d_lsa_80_True_umap_euclidean_15_0.1_random_1.0_None_None.png




.. GENERATED FROM PYTHON SOURCE LINES 404-405

The plots for 2D map with clustering is saved under pipeline cluster directory.

.. GENERATED FROM PYTHON SOURCE LINES 405-409

.. code-block:: Python


    for file in pipeline.get_clus_dir().glob("*.png"):
        print(file)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    /builds/2mk6rsew/0/hgozukan/cartolabe-data/dumps/lisn/2.0.0/mat_articles__authors_4_teams_4_labs_4_words_en_abstract_s_en_title_s_en_keyword_s_en_domainAllCodeLabel_fs_10_0.05_None_None_5_4/lsa_80_True/umap_euclidean_15_0.1_random_1.0_None_None/hdbscan_3/lisn_2.0.0_15d3d1d060e5f28d_lsa_80_True_umap_euclidean_15_0.1_random_1.0_None_None_hdbscan_hl_clusters.png
    /builds/2mk6rsew/0/hgozukan/cartolabe-data/dumps/lisn/2.0.0/mat_articles__authors_4_teams_4_labs_4_words_en_abstract_s_en_title_s_en_keyword_s_en_domainAllCodeLabel_fs_10_0.05_None_None_5_4/lsa_80_True/umap_euclidean_15_0.1_random_1.0_None_None/hdbscan_3/lisn_2.0.0_15d3d1d060e5f28d_lsa_80_True_umap_euclidean_15_0.1_random_1.0_None_None_hdbscan_ml_clusters.png




.. GENERATED FROM PYTHON SOURCE LINES 410-424

Nearest neighbors
----------------------------

One more thing which could be useful to appreciate the quality of our data
would be to get each point's nearest neighbors. If our data processing is
done correctly, we expect the related articles, labs, words and authors to be
located close to each other.

Finding nearest neighbors is a common task with various algorithms aiming to
solve it. The `find_neighbors` method uses one of these algorithms to find the
nearest points of all entities (articles, authors, teams,
labs, words). It takes an optional weight parameter to tweak
the distance calculation to select points that have a higher score but are
maybe a bit farther instead of just selecting the closest neighbors.

.. GENERATED FROM PYTHON SOURCE LINES 424-437

.. code-block:: Python


    from cartodata.pipeline.neighbors import AllNeighbors

    n_neighbors = 10
    weights = [0, 0.5, 0.5, 0, 0]

    neighboring = AllNeighbors(n_neighbors=n_neighbors, power_scores=weights)

    pipeline.set_neighboring(neighboring)

    pipeline.find_neighbors()









.. GENERATED FROM PYTHON SOURCE LINES 438-462

Export file using exporter
===========================

We can now export the data. To export the data, we need to configure the exporter.

The exported data will be the points extracted from the dataset corresponding to the entities that we have defined.

In the export file, we will have the following columns for each point:


| column | value |
---------|-------------|
| nature |  one of articles, authors, teams, labs, words |
| label | point's label |
| score | point's score |
| rank |  point's rank |
| x | point's x location on the map |
| y | point's y location on the map |
| nn_articles | neighboring articles to this point |
| nn_teams | neighboring teams to this point |
| nn_labs | neighboring labs to this point |
| nn_words | neighboring words to this point |

we will call `pipeline.export` function. It will create `export.feather` file and save under `pipeline.working_dir`.

.. GENERATED FROM PYTHON SOURCE LINES 462-465

.. code-block:: Python


    pipeline.export()








.. GENERATED FROM PYTHON SOURCE LINES 466-467

Let's display the contents of the file. The file is saved under the pipeline cluster directory.

.. GENERATED FROM PYTHON SOURCE LINES 467-473

.. code-block:: Python


    import pandas as pd # noqa

    df = pd.read_feather(pipeline.get_clus_dir() / "export.feather")
    df.head()






.. raw:: html

    <div class="output_subarea output_html rendered_html output_result">
    <div>
    <style scoped>
        .dataframe tbody tr th:only-of-type {
            vertical-align: middle;
        }

        .dataframe tbody tr th {
            vertical-align: top;
        }

        .dataframe thead th {
            text-align: right;
        }
    </style>
    <table border="1" class="dataframe">
      <thead>
        <tr style="text-align: right;">
          <th></th>
          <th>nature</th>
          <th>label</th>
          <th>score</th>
          <th>rank</th>
          <th>x</th>
          <th>y</th>
          <th>nn_articles</th>
          <th>nn_authors</th>
          <th>nn_teams</th>
          <th>nn_labs</th>
          <th>nn_words</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>0</th>
          <td>articles</td>
          <td>Termination and Confluence of Higher-Order Rew...</td>
          <td>1.0</td>
          <td>0</td>
          <td>9.309070</td>
          <td>6.332092</td>
          <td>0,30,2057,15,17,13,18,432,41,815</td>
          <td>4329,4273,4368,4540,4543,4541,4374,4310,4295,4673</td>
          <td>4956,4964,4974,4963,4982,4960,4969,4977,4966,4961</td>
          <td>5137,5189,5397,5118,5439,5214,5537,5506,5033,5112</td>
          <td>8544,7461,9230,9812,9231,7610,9967,6031,7459,6261</td>
        </tr>
        <tr>
          <th>1</th>
          <td>articles</td>
          <td>Efficient Self-stabilization</td>
          <td>1.0</td>
          <td>1</td>
          <td>7.495029</td>
          <td>1.892885</td>
          <td>1,358,22,233,409,60,878,1941,34,212</td>
          <td>4271,4262,4385,4389,4273,4303,4282,4538,4408,4402</td>
          <td>4956,4964,4963,4974,4957,4982,4977,4969,4960,4958</td>
          <td>5024,5113,5106,5439,5012,5190,5031,5041,5077,5200</td>
          <td>9579,9580,9991,6775,9916,6776,9581,6953,9163,8575</td>
        </tr>
        <tr>
          <th>2</th>
          <td>articles</td>
          <td>Resource-bounded relational reasoning: inducti...</td>
          <td>1.0</td>
          <td>2</td>
          <td>8.351049</td>
          <td>8.060863</td>
          <td>2,196,2615,2248,3961,134,1050,1463,2423,580</td>
          <td>4437,4345,4368,4680,4411,4603,4722,4480,4310,4684</td>
          <td>4956,4964,4963,4974,4969,4960,4977,4966,4962,4961</td>
          <td>5289,5183,5358,5406,5137,5479,5144,5153,5397,5306</td>
          <td>7945,7620,7610,8431,8999,5768,6247,6087,7621,9269</td>
        </tr>
        <tr>
          <th>3</th>
          <td>articles</td>
          <td>Reasoning about generalized intervals : Horn r...</td>
          <td>1.0</td>
          <td>3</td>
          <td>8.333518</td>
          <td>0.076816</td>
          <td>3,1597,2995,2988,1505,2529,2884,1909,1934,3352</td>
          <td>4657,4323,4480,4520,4815,4357,4374,4266,4757,4537</td>
          <td>4956,4964,4963,4974,4982,4969,4977,4966,4960,4962</td>
          <td>5119,5351,5386,5120,4997,5003,5185,4995,5121,5531</td>
          <td>5670,5672,6228,7414,6480,8672,9238,9688,7609,7752</td>
        </tr>
        <tr>
          <th>4</th>
          <td>articles</td>
          <td>Proof Nets and Explicit Substitutions</td>
          <td>1.0</td>
          <td>4</td>
          <td>9.304070</td>
          <td>6.326972</td>
          <td>4,15,17,2049,2909,30,41,1996,18,2545</td>
          <td>4673,4433,4541,4333,4430,4540,4371,4543,4679,4429</td>
          <td>4956,4964,4963,4974,4982,4960,4969,4977,4961,4958</td>
          <td>5137,5397,5479,5118,5006,5406,5189,5400,5007,5291</td>
          <td>6031,9967,9812,7826,8646,7461,7610,6570,6395,8645</td>
        </tr>
      </tbody>
    </table>
    </div>
    </div>
    <br />
    <br />

.. GENERATED FROM PYTHON SOURCE LINES 474-477

This is a basic export file. For each point, we can add additional columns.

For example, for each author, we can add **labs** and **teams** columns to list the labs and teams that the author belongs to. We can also merge the teams and labs in one column and name it as labs. To do that we have to first create export config for the entity (nature) that we would like to modify. 

.. GENERATED FROM PYTHON SOURCE LINES 477-487

.. code-block:: Python


    from cartodata.pipeline.exporting import (
        ExportNature, MetadataColumn
    ) # noqa

    ex_author = ExportNature(key="authors", 
                             refs=["labs", "teams"], 
                             merge_metadata=[{"columns": ["teams", "labs"], 
                                              "as_column": "labs"}])








.. GENERATED FROM PYTHON SOURCE LINES 488-491

We can do the same for articles. Each article will have **teams** and **labs** data, and additionally **author** of the article. So we can set `refs=["labs", "teams", "authors"]`. 

The original dataset contains a column `producedDateY_i` which contains the year that the article is published. We can add this data as metadata for the point but updating column name with a more clear alternative `year`. We can also add a function to apply to the column value. In this example we will convert column value to string.

.. GENERATED FROM PYTHON SOURCE LINES 491-495

.. code-block:: Python


    meta_year_article = MetadataColumn(column="producedDateY_i", as_column="year", 
                                       func="x.astype(str)")








.. GENERATED FROM PYTHON SOURCE LINES 496-497

We will also add `halId_s` column as `url` and set empty string if the value does not exist:

.. GENERATED FROM PYTHON SOURCE LINES 497-508

.. code-block:: Python


    meta_url_article = MetadataColumn(column="halId_s", as_column="url", func="x.fillna('')")

    ""
    ex_article = ExportNature(key="articles", refs=["labs", "teams", "authors"], 
                             merge_metadata=[{"columns": ["teams", "labs"], 
                                              "as_column": "labs"}],
                             add_metadata=[meta_year_article, meta_url_article])

    pipeline.export(export_natures=[ex_article, ex_author])








.. GENERATED FROM PYTHON SOURCE LINES 509-510

Now we can load the new `export.feather` file to see the difference.

.. GENERATED FROM PYTHON SOURCE LINES 510-515

.. code-block:: Python


    df = pd.read_feather(pipeline.get_clus_dir()/ "export.feather")

    df.head()






.. raw:: html

    <div class="output_subarea output_html rendered_html output_result">
    <div>
    <style scoped>
        .dataframe tbody tr th:only-of-type {
            vertical-align: middle;
        }

        .dataframe tbody tr th {
            vertical-align: top;
        }

        .dataframe thead th {
            text-align: right;
        }
    </style>
    <table border="1" class="dataframe">
      <thead>
        <tr style="text-align: right;">
          <th></th>
          <th>nature</th>
          <th>label</th>
          <th>score</th>
          <th>rank</th>
          <th>x</th>
          <th>y</th>
          <th>nn_articles</th>
          <th>nn_authors</th>
          <th>nn_teams</th>
          <th>nn_labs</th>
          <th>nn_words</th>
          <th>labs</th>
          <th>authors</th>
          <th>year</th>
          <th>url</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>0</th>
          <td>articles</td>
          <td>Termination and Confluence of Higher-Order Rew...</td>
          <td>1.0</td>
          <td>0</td>
          <td>9.309070</td>
          <td>6.332092</td>
          <td>0,30,2057,15,17,13,18,432,41,815</td>
          <td>4329,4273,4368,4540,4543,4541,4374,4310,4295,4673</td>
          <td>4956,4964,4974,4963,4982,4960,4969,4977,4966,4961</td>
          <td>5137,5189,5397,5118,5439,5214,5537,5506,5033,5112</td>
          <td>8544,7461,9230,9812,9231,7610,9967,6031,7459,6261</td>
          <td>,4992,4991,4990,4989</td>
          <td></td>
          <td>2000</td>
          <td>inria-00105556</td>
        </tr>
        <tr>
          <th>1</th>
          <td>articles</td>
          <td>Efficient Self-stabilization</td>
          <td>1.0</td>
          <td>1</td>
          <td>7.495029</td>
          <td>1.892885</td>
          <td>1,358,22,233,409,60,878,1941,34,212</td>
          <td>4271,4262,4385,4389,4273,4303,4282,4538,4408,4402</td>
          <td>4956,4964,4963,4974,4957,4982,4977,4969,4960,4958</td>
          <td>5024,5113,5106,5439,5012,5190,5031,5041,5077,5200</td>
          <td>9579,9580,9991,6775,9916,6776,9581,6953,9163,8575</td>
          <td>,4992,4991,4990,4989</td>
          <td>4262</td>
          <td>2000</td>
          <td>tel-00124843</td>
        </tr>
        <tr>
          <th>2</th>
          <td>articles</td>
          <td>Resource-bounded relational reasoning: inducti...</td>
          <td>1.0</td>
          <td>2</td>
          <td>8.351049</td>
          <td>8.060863</td>
          <td>2,196,2615,2248,3961,134,1050,1463,2423,580</td>
          <td>4437,4345,4368,4680,4411,4603,4722,4480,4310,4684</td>
          <td>4956,4964,4963,4974,4969,4960,4977,4966,4962,4961</td>
          <td>5289,5183,5358,5406,5137,5479,5144,5153,5397,5306</td>
          <td>7945,7620,7610,8431,8999,5768,6247,6087,7621,9269</td>
          <td>,4992,4990,4989,4991,4994,4993</td>
          <td>4263</td>
          <td>2000</td>
          <td>hal-00111312</td>
        </tr>
        <tr>
          <th>3</th>
          <td>articles</td>
          <td>Reasoning about generalized intervals : Horn r...</td>
          <td>1.0</td>
          <td>3</td>
          <td>8.333518</td>
          <td>0.076816</td>
          <td>3,1597,2995,2988,1505,2529,2884,1909,1934,3352</td>
          <td>4657,4323,4480,4520,4815,4357,4374,4266,4757,4537</td>
          <td>4956,4964,4963,4974,4982,4969,4977,4966,4960,4962</td>
          <td>5119,5351,5386,5120,4997,5003,5185,4995,5121,5531</td>
          <td>5670,5672,6228,7414,6480,8672,9238,9688,7609,7752</td>
          <td>,4992,5005,5004,5003,5002,5001,5000,4999,4998,...</td>
          <td></td>
          <td>2000</td>
          <td>hal-03300321</td>
        </tr>
        <tr>
          <th>4</th>
          <td>articles</td>
          <td>Proof Nets and Explicit Substitutions</td>
          <td>1.0</td>
          <td>4</td>
          <td>9.304070</td>
          <td>6.326972</td>
          <td>4,15,17,2049,2909,30,41,1996,18,2545</td>
          <td>4673,4433,4541,4333,4430,4540,4371,4543,4679,4429</td>
          <td>4956,4964,4963,4974,4982,4960,4969,4977,4961,4958</td>
          <td>5137,5397,5479,5118,5006,5406,5189,5400,5007,5291</td>
          <td>6031,9967,9812,7826,8646,7461,7610,6570,6395,8645</td>
          <td>,4992,4990,4989,4991,5008,4994,5007,5006</td>
          <td></td>
          <td>2000</td>
          <td>hal-00384955</td>
        </tr>
      </tbody>
    </table>
    </div>
    </div>
    <br />
    <br />

.. GENERATED FROM PYTHON SOURCE LINES 516-519

For the points of nature **articles**, we have additional **labs**, **authors**, **year**, **url** columns.

Let's see the points of nature **authors**:

.. GENERATED FROM PYTHON SOURCE LINES 519-522

.. code-block:: Python


    df[df["nature"] == "authors"].head()






.. raw:: html

    <div class="output_subarea output_html rendered_html output_result">
    <div>
    <style scoped>
        .dataframe tbody tr th:only-of-type {
            vertical-align: middle;
        }

        .dataframe tbody tr th {
            vertical-align: top;
        }

        .dataframe thead th {
            text-align: right;
        }
    </style>
    <table border="1" class="dataframe">
      <thead>
        <tr style="text-align: right;">
          <th></th>
          <th>nature</th>
          <th>label</th>
          <th>score</th>
          <th>rank</th>
          <th>x</th>
          <th>y</th>
          <th>nn_articles</th>
          <th>nn_authors</th>
          <th>nn_teams</th>
          <th>nn_labs</th>
          <th>nn_words</th>
          <th>labs</th>
          <th>authors</th>
          <th>year</th>
          <th>url</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>4262</th>
          <td>authors</td>
          <td>Sébastien Tixeuil</td>
          <td>47.0</td>
          <td>4262</td>
          <td>9.475885</td>
          <td>-4.045297</td>
          <td>1332,1944,683,237,1717,282,1600,2373,2449,2075</td>
          <td>4262,4408,4375,4274,4275,4721,4397,4745,4858,4273</td>
          <td>4957,4956,4964,4960,4963,4974,4982,4969,4977,4962</td>
          <td>5200,5031,5179,5032,5384,5320,5319,5449,5468,5456</td>
          <td>6023,7554,7332,7555,8341,9243,8125,9756,6776,9744</td>
          <td>4957,4960,4989,4990,4991,4992,5008,5012,5021,5...</td>
          <td>None</td>
          <td>None</td>
          <td>None</td>
        </tr>
        <tr>
          <th>4263</th>
          <td>authors</td>
          <td>Michèle Sebag</td>
          <td>137.0</td>
          <td>4263</td>
          <td>3.732471</td>
          <td>4.000053</td>
          <td>2523,1861,2292,3316,641,2612,892,853,4241,782</td>
          <td>4263,4293,4411,4341,4706,4315,4273,4480,4449,4483</td>
          <td>4956,4964,4963,4974,4982,4969,4962,4977,4966,4960</td>
          <td>5216,5288,5432,5029,5523,4990,5307,5049,5208,4989</td>
          <td>9228,6895,6237,6899,8074,7104,7869,9229,7100,8851</td>
          <td>4956,4964,4972,4989,4990,4991,4992,4993,4994,4...</td>
          <td>None</td>
          <td>None</td>
          <td>None</td>
        </tr>
        <tr>
          <th>4264</th>
          <td>authors</td>
          <td>Khaldoun Al Agha</td>
          <td>20.0</td>
          <td>4264</td>
          <td>6.910202</td>
          <td>2.698025</td>
          <td>3434,2475,2773,2878,562,1389,474,2879,573,1366</td>
          <td>4264,4419,4783,4400,4547,4546,4691,4262,4273,4402</td>
          <td>4965,4956,4964,4963,4974,4982,4969,4977,4960,4962</td>
          <td>5410,5009,5113,5213,5077,5194,5305,5298,5361,5285</td>
          <td>10156,10155,10157,8263,7906,8483,9281,8482,996...</td>
          <td>4965,4989,4990,4991,4992,4993,5000,5008,5009,5...</td>
          <td>None</td>
          <td>None</td>
          <td>None</td>
        </tr>
        <tr>
          <th>4265</th>
          <td>authors</td>
          <td>Ralf Treinen</td>
          <td>5.0</td>
          <td>4265</td>
          <td>7.944470</td>
          <td>-0.504129</td>
          <td>191,6,192,1438,21,3108,277,2307,2072,831</td>
          <td>4265,4299,4603,4329,4292,4300,4466,4746,4368,4353</td>
          <td>4956,4964,4963,4974,4982,4977,4966,4969,4960,4962</td>
          <td>5047,5010,5044,5134,5088,5232,5105,5098,5152,5137</td>
          <td>5871,6547,6068,7245,7246,7247,7833,7834,5873,6955</td>
          <td>4974,4989,4990,4991,4992,4994,5006,5007,5008,5...</td>
          <td>None</td>
          <td>None</td>
          <td>None</td>
        </tr>
        <tr>
          <th>4266</th>
          <td>authors</td>
          <td>Christine Eisenbeis</td>
          <td>27.0</td>
          <td>4266</td>
          <td>2.767531</td>
          <td>2.531678</td>
          <td>1149,1025,1414,1384,638,527,1171,65,338,899</td>
          <td>4266,4505,4278,4329,4267,4303,4644,4273,4400,4766</td>
          <td>4956,4964,4963,4974,4982,4958,4977,4969,4960,4973</td>
          <td>5314,5162,5260,5133,5309,5219,5040,5027,5393,5382</td>
          <td>9716,6160,8678,7678,6159,6219,7676,9907,7387,8887</td>
          <td>4958,4989,4990,4991,4992,4994,4996,5006,5007,5...</td>
          <td>None</td>
          <td>None</td>
          <td>None</td>
        </tr>
      </tbody>
    </table>
    </div>
    </div>
    <br />
    <br />

.. GENERATED FROM PYTHON SOURCE LINES 523-526

We have values for labs field, but not for authors, year, or url field.

As we have not defined any relation for points of natures **teams**, **labs** and **words**, these new columns are empty for those points.

.. GENERATED FROM PYTHON SOURCE LINES 526-538

.. code-block:: Python


    df[df["nature"] == "teams"].head()

    ""
    df[df["nature"] == "labs"].head()

    ""
    df[df["nature"] == "words"].head()

    ""
    df['x'][1]





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    7.495028972625732



.. GENERATED FROM PYTHON SOURCE LINES 539-541

Hierarchical Directory Structure
=================================

.. GENERATED FROM PYTHON SOURCE LINES 543-546

It is possible to save the files generated by pipeline in a hierarchical directory structure. The advantage for this is to be able to use the same matrices whenever the parameters are the same, and regenerate new ones, once there is a change of parameters in a particular step. The previous processing will not be deleted, and it will enable us to compare the results of multiple runs on the same dataset with different parameters.

`pipeline.working_dir` is the top directory that for a processing. It is named with dataset column parameters. The entity matrices and all following processing artifacts are saved under this directory.

.. GENERATED FROM PYTHON SOURCE LINES 546-549

.. code-block:: Python


    pipeline.working_dir





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    PosixPath('/builds/2mk6rsew/0/hgozukan/cartolabe-data/dumps/lisn/2.0.0/mat_articles__authors_4_teams_4_labs_4_words_en_abstract_s_en_title_s_en_keyword_s_en_domainAllCodeLabel_fs_10_0.05_None_None_5_4')



.. GENERATED FROM PYTHON SOURCE LINES 550-551

nD processing dumps are saved under `pipeline.working_dir / nD_dir`.

.. GENERATED FROM PYTHON SOURCE LINES 551-554

.. code-block:: Python


    pipeline.get_nD_dir()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    PosixPath('/builds/2mk6rsew/0/hgozukan/cartolabe-data/dumps/lisn/2.0.0/mat_articles__authors_4_teams_4_labs_4_words_en_abstract_s_en_title_s_en_keyword_s_en_domainAllCodeLabel_fs_10_0.05_None_None_5_4/lsa_80_True')



.. GENERATED FROM PYTHON SOURCE LINES 555-556

2D processing dumps are saved under `pipeline.working_dir / nD_dir / 2D_dir`.

.. GENERATED FROM PYTHON SOURCE LINES 556-559

.. code-block:: Python


    pipeline.get_2D_dir()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    PosixPath('/builds/2mk6rsew/0/hgozukan/cartolabe-data/dumps/lisn/2.0.0/mat_articles__authors_4_teams_4_labs_4_words_en_abstract_s_en_title_s_en_keyword_s_en_domainAllCodeLabel_fs_10_0.05_None_None_5_4/lsa_80_True/umap_euclidean_15_0.1_random_1.0_None_None')



.. GENERATED FROM PYTHON SOURCE LINES 560-561

Clustering dumps are saved under `pipeline.working_dir / nD_dir / 2D_dir/ clus_dir`.

.. GENERATED FROM PYTHON SOURCE LINES 561-564

.. code-block:: Python


    pipeline.get_clus_dir()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    PosixPath('/builds/2mk6rsew/0/hgozukan/cartolabe-data/dumps/lisn/2.0.0/mat_articles__authors_4_teams_4_labs_4_words_en_abstract_s_en_title_s_en_keyword_s_en_domainAllCodeLabel_fs_10_0.05_None_None_5_4/lsa_80_True/umap_euclidean_15_0.1_random_1.0_None_None/hdbscan_3')



.. GENERATED FROM PYTHON SOURCE LINES 565-566

Neighboring dumps are saved under `pipeline.working_dir / nD_dir / 2D_dir/ neigbors_dir`.

.. GENERATED FROM PYTHON SOURCE LINES 566-569

.. code-block:: Python


    pipeline.get_neighbors_dir()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    PosixPath('/builds/2mk6rsew/0/hgozukan/cartolabe-data/dumps/lisn/2.0.0/mat_articles__authors_4_teams_4_labs_4_words_en_abstract_s_en_title_s_en_keyword_s_en_domainAllCodeLabel_fs_10_0.05_None_None_5_4/lsa_80_True/neighbors_10_0_0.5_0.5_0_0')



.. GENERATED FROM PYTHON SOURCE LINES 570-571

Let's assume that we want to run UMAP with different parameters.

.. GENERATED FROM PYTHON SOURCE LINES 571-584

.. code-block:: Python


    from cartodata.pipeline.projection2d import UMAPProjection  # noqa


    umap_projection = UMAPProjection(n_neighbors=30, min_dist=0.3)

    pipeline.set_projection_2d(umap_projection)
    matrices_2D = pipeline.do_projection_2D()
    labels = tuple(pipeline.natures)
    colors = ['b', 'r', 'c', 'y', 'm']

    fig, ax = pipeline.plot_map(matrices_2D, labels, colors)




.. image-sg:: /auto_examples/images/sphx_glr_pipeline_lisn_lsa_umap_hdbscan_hierarchical_004.png
   :alt: pipeline lisn lsa umap hdbscan hierarchical
   :srcset: /auto_examples/images/sphx_glr_pipeline_lisn_lsa_umap_hdbscan_hierarchical_004.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 585-586

If we list the contents of nD directory, we will see two directories for umap projection.

.. GENERATED FROM PYTHON SOURCE LINES 586-591

.. code-block:: Python


    dir_nD = pipeline.get_nD_dir()

    ""
    # !ls $dir_nD




.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    ''




.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 47.179 seconds)


.. _sphx_glr_download_auto_examples_pipeline_lisn_lsa_umap_hdbscan_hierarchical.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: pipeline_lisn_lsa_umap_hdbscan_hierarchical.ipynb <pipeline_lisn_lsa_umap_hdbscan_hierarchical.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: pipeline_lisn_lsa_umap_hdbscan_hierarchical.py <pipeline_lisn_lsa_umap_hdbscan_hierarchical.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: pipeline_lisn_lsa_umap_hdbscan_hierarchical.zip <pipeline_lisn_lsa_umap_hdbscan_hierarchical.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_