Skip to content
ImagineWorld

Text Analytics and NLP Using Graphs

node_idnode-book_graph-machine-learning_chapter-08-text-analytics-and-nlp-using-graphs
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleText Analytics and NLP Using Graphs
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 08: Text Analytics and NLP Using Graphs

Section titled “Chapter 08: Text Analytics and NLP Using Graphs”

Graph-based NLP — knowledge graphs, bipartite document/entity graphs, entity-entity graphs, document-document graphs, document topic classification with shallow methods and GNNs.

Nowadays, a vast amount of information is available in the form of text in natural written language. The very book you are reading right now is one such example. The news you read every morning, the messages or Facebook posts you send or read, the reports you write for school assignments, and the emails you write are all examples of information that is exchanged via written documents and text. It is undoubtedly the most common way of indirect interaction, as opposed to direct interaction, such as talking or gesticulating. It is, therefore, crucial to utilize this kind of information and extract insights from documents and texts. This abundance of textual information has driven significant advancements in natural language processing (NLP). One notable development is ChatGPT, which provides sophisticated conversational capabilities. However, like many other NLP algorithms, ChatGPT is not natively designed to exploit inherent relationships and structures present in text data. As we are learning throughout this book, indeed, such relationships are everywhere and, if properly leveraged, can significantly benefit machine learning. For example, graphs can represent connections between entities, dependencies in sentences, or semantic relationships across documents. By integrating graphs into NLP workflows, we can enhance tasks such as information retrieval, question answering, and recommendation systems. Moreover, graph-based methods often improve the explainability and robustness of models, offering insights into the underlying relationships that would otherwise be overlooked by traditional NLP approaches.

In this chapter, we will show you how to process natural language texts and review some basic models that allow structuring text information. Using the information extracted from a corpus of documents, we will show you how to create networks that can be analyzed using some of the techniques we have seen in previous chapters. In particular, using a tagged corpus, we will show you how to develop both semi-supervised (classification models to classify documents in pre-determined topics) and unsupervised (community detection to discover new topics) algorithms.

The chapter is organized as follows:

  • Providing a quick overview of a dataset – the Reuters-21578 dataset
  • Understanding the main concepts and tools used in NLP
  • Creating graphs from a corpus of documents
  • Building a document topic classifier

In order to show you how to process a corpus of documents with the aim of extracting relevant information, we will be using a dataset derived from a well-known benchmark in the field of NLP: the so-called Reuters-21578 dataset. The original dataset includes a set of 21,578 news articles published in the Reuters financial newswire in 1987, which were assembled and indexed in categories. The original dataset has a very skewed distribution, with some categories appearing in only the training set or the test set. For this reason, we use a modified version named ApteMod, also referred to as Reuters-21578 Distribution 1.0, which has a lesser skew distribution and consistent labels between training and test datasets.

Despite the fact that the news articles in the Reuters financial newswire are a bit outdated, the dataset has been used in a plethora of papers on NLP and still represents a dataset often used for benchmarking algorithms. Nevertheless, the Reuters-21578 dataset is much smaller in size in comparison to other datasets available today, which can comprise millions or billions of documents. Hence, if you wish to scale your application and analysis, using a dataset with a larger number of documents is advisable (see, for instance, https://github.com/niderhoff/nlp-datasets for an overview of the most common ones).

It is important to note that these may require larger storage and computational power to allow their processing. In Chapter 10, Building a Data-Driven Graph-Powered Application, we will show you some of the tools and libraries that can help you scale your analysis.

Let’s overview the dataset: each document of the Reuters-21578 dataset is provided with a set of labels that represent its content and make it a perfect benchmark for testing both supervised and unsupervised algorithms. The Reuters-21578 dataset can be easily download using the nltk library (which is a very useful library for post-processing documents):

from nltk.corpus import reuters
corpus = pd.DataFrame([
{"id": _id,
"text": reuters.raw(_id).replace("\n", ""),
"label": reuters.categories(_id)}
for _id in reuters.fields()
])

As you will see by inspecting the DataFrame corpus, the IDs have the form training/{ID} and test/{ID}, making it clear which documents should be used for training and which for testing. To start with, let us list all the topics and see the number of documents per topic using the following code:

from collections import Counter
Counter([label for document_labels in corpus["label"] for label in document_labels]).most_common()

The Reuters-21578 dataset includes 90 different topics with a significant degree of unbalance between classes, with almost 37% of the documents in the most common category and only 0.01% in each of the five least common categories. As you can see from inspecting the text, some of the documents have some new-line characters embedded. These artifacts are common in raw text data and can interfere with text processing tasks, such as tokenization, which is a fundamental step in most NLP pipelines (as we will see later). If not removed, such artifacts can lead to tokenization errors, where words or phrases are incorrectly split, resulting in noisy or inconsistent data representations. This can degrade the performance of downstream NLP algorithms. To address this issue, we can easily clean the text by removing newline characters during the preprocessing stage, as follows:

corpus["clean_text"] = corpus["text"].apply(
lambda x: x.replace("\n", "")
)

Now that we have loaded the data in memory, we can start analyzing it. In the next section, we will show you some of the main tools that can be used when dealing with unstructured text data to extract structured information that can be more easily used.

Understanding the main concepts and tools used in NLP

Section titled “Understanding the main concepts and tools used in NLP”

When processing documents, the first analytical step is certainly to infer the document language. Most analytical engines used in NLP tasks are in fact trained on documents that have a specific language and should only be used for such a language. Although attempts to build cross-language models (see, for instance, multi-lingual embeddings such as https://fasttext.cc/docs/en/aligned-vectors.html and https://github.com/google-research/bert/blob/master/multilingual.md) have recently gained increasing popularity, these models face challenges, such as lower performance compared to language-specific models and difficulty in handling languages with sparse training data or significantly different syntax and grammatical structures. For these reasons, they still represent a small portion of NLP models. It is, therefore, very common to first infer the language to use the correct downstream analytical NLP pipeline.

In order to infer the language, different methods can be used. One very simple yet effective approach relies on looking for the most common words of a language (so-called stopwords) and building a score based on their frequencies. Its precision, however, tends to be limited for short text and does not make use of the word positioning and context. On the other hand, Python has many libraries that, using more elaborate logic, allow inferring the language in a more precise manner. Some examples of these libraries are fasttext, polyglot, and langdetect, to name just a few.

As an example, we will use langdetect in the following code example, which can be integrated with very few lines and provides support for more than 150 languages. The language can be inferred for all documents using the following snippet:

from langdetect import detect
import numpy as np
def getLanguage(text: str):
try:
return langdetect.detect(text)
except:
return np.nan
corpus["language"] = corpus["text"].apply(langdetect.detect)

As you will see in the output, there seem to be documents in languages other than English. Indeed, these documents often are either very short or have a strange structure that does not seem to be actual news. When documents represent text that a human would read and label as news, the model is generally rather precise and accurate.

Now that we have inferred the language, we can continue with the language-dependent steps of the analytical pipeline. Documents in languages other than English will now be filtered out, as these are indeed a very small part of the dataset (also given that the dataset is built by documents in English and that, for the sake of simplicity, the models that we are going to use in this example are specific to English text). Of course, should the number of non-English documents be larger and more significant, and dropping them were not an option, you could either first translate the non-English documents into English using appropriate text-to-text translation models (like Google Translate) or split the analytical pipeline into multiple sub-pipelines depending on the document language.

For the following tasks, we will be using spacy, which is an extremely powerful library that allows us to embed state-of-the- art NLP models with very few lines of code. After installing the library with pip install spacy, language-specific models can be integrated by simply installing them using the spacy download utility. For instance, the following command can be used in order to download and install the English model:

Terminal window
python -m spacy download en_core_web_sm

Now we should have the language models in English ready to use. Let’s then see which information it can provide to us. Using spacy is extremely simple; in just one line of embedded code, a very rich set of information can be embedded. Let us start by applying the model to one of the documents in the Reuters corpus, presented in the following callout box:

SUBROTO SAYS INDONESIA SUPPORTS TIN PACT EXTENSION

Mines and Energy Minister Subroto confirmed Indonesian support for an extension of the sixth International Tin Agreement (ITA), but said a new pact was not necessary. Asked by Reuters to clarify his statement on Monday in which he said the pact should be allowed to lapse, Subroto said Indonesia was ready to back extension of the ITA. “We can support extension of the sixth agreement,” he said. “But a seventh accord we believe to be unnecessary.” The sixth ITA will expire at the end of June unless a two-thirds majority of members vote for an extension.

spacy can be easily applied by just loading the model and applying it to the text:

nlp = spacy.load('en_core_web_md')
parsed = nlp(text)

The object parsed, returned by spacy, has several fields that result from the application of many models that are combined into a single pipeline. These provide a different level of text structuring that we will examine one by one:

  • Text segmentation and tokenization, which is the process aimed at splitting a document into its periods, sentences, and single words (or tokens). This step is generally very important for all subsequent analyses and it usually uses punctuation, blank-spaces, and new lines, in order to infer the best document segmentation. The segmentation engine provided in spacy generally works fairly well. However, please note that depending on the context, a bit of model tuning or rule modification might be necessary. For instance, when dealing with short texts that have slang, emoticons, links, and hashtags, a better choice for text segmentation and tokenization may be the TweetTokenizer included in the nltk library. Depending on the context, we encourage you to explore other possible segmentations available.

In the document returned by spacy, the segmentation in sentences can be found in the sents attribute of the parsed object. Each sentence can be iterated over its token by simply using:

for sent in parsed.sents:
for token in sent:
print(token)

Each token is a spacy Span object that has attributes that specify the type of token and further characterization that is introduced by the other models.

  • Part-of-speech tagging. Once the text has been divided into its single words (also referred to as tokens), the next step is to associate each token to a part-of-speech (PoS) tag, that is to say, its grammatical type. The inferred tags are usually nouns, verbs, auxiliary verbs, adjectives, and so on. The engines used for PoS tagging are usually models that are trained to classify tokens based on a large, labeled corpus, where each token has an associated PoS tag. Being trained on actual data, they learn to recognize common patterns within a language, for instance, the word “the” (which is a determinative article (DET) is usually followed by a noun, and so on. When using spacy, the information about the PoS tagging is usually stored in the label_ attribute of the Span object. The types of tags available can be found at https://spacy.io/models/en. Conversely, you can get a human-readable value for a given type using the function spacy.explain.

  • Named entity recognition. This analytical step is generally a statistical model that is trained to recognize the type of nouns that appear within the text. Some common examples of entities are organization, person, geographic location and addresses, products, numbers, and currencies. Given the context (the surrounding words) as well as the prepositions that are used, the model infers the most probable type of the entity, if any. As in other steps of the NLP pipeline, these models are also usually trained using a large, tagged dataset on which they learn common patterns and structure. In spacy, the information about the document entities is usually stored in the ents attribute of the parsed object. spacy also provides some utilities to nicely visualize the entities in a text, using the displacy module:

    displacy.render(parsed, style='ent', jupyter=True)

This gives the following output:

Figure 8.1: Example of the spacy output for the named entity recognition engine

Figure 8.1: Example of the spacy output for the named entity recognition engine

  • Dependency parsing. The dependency parser is an extremely powerful engine that infers the relationships between tokens within a sentence. It basically allows you to build a syntactic tree of how words are related to each other. Let’s, for instance, take a simple example taken from the spacy website: Autonomous cars shift insurance liability towards manufacturers.

Figure 8.2 shows the dependency tree, where it can be seen that the main verb (or root) “shift” is related by the subject-object relationship to “cars” (subject) and “liability” (object). It also sustains the preposition “towards.” In the same way, the remaining nouns/adjectives “Autonomous,” “insurance,” and “manufacturers” are related to either the subject, the object, or the preposition. Thus, spacy can be used to build a syntactic tree that can be navigated in order to identify relationships between the tokens:

Figure 8.2: Example of a syntactic dependency tree provided by spacy

Figure 8.2: Example of a syntactic dependency tree provided by spacy

As we will see in the following section, this information can be crucial when building knowledge graphs.

  • Lemmatization or stemming. Finally, the very last step of the analytical pipeline is aimed at reducing words to a common root to provide a cleaner version, and limiting the morphological variation of words. Take, for instance, the verb to be. It can have many morphological variations, such as “is,” “are,” “was,” etc. which are all different valid forms. Or also consider the difference between “car” and “cars.” In most cases, we are not interested in these small differences introduced by morphology. The lemmatizers and stemmers help to reduce tokens to a common, stable form that can be more easily processed. Usually, the lemmatizer is based on a set of rules that associate particular words (with conjugation, plurals, and inflection) to a common root form. More elaborate implementations may also use the context and the PoS tagging information in order to be more robust against homonyms. On the other hand, stemmers are generally simpler, and instead of associating words to a common root form, they usually remove the last part of the word to deal with inflectional and derivational variance. Also, stemmers are generally based on a set of rules that remove a certain pattern, rather than taking into account lexica and syntactic information or using extensive vocabulary mappings. In spacy, the lemmatized version of a token can be found in the Span object via the lemma_ attribute.

As shown below, spacy pipelines can be easily integrated in order to process the entire corpus and store the results in our corpus DataFrame:

nlp = spacy.load('en_core_web_md')
sample_corpus["parsed"] = sample_corpus["clean_text"]\
.apply(nlp)

This DataFrame represents the structured information of the documents that will be the base of all our subsequent analysis. In particular, in the next section we will show you how to build graphs starting from such information.

Creating graphs from a corpus of documents

Section titled “Creating graphs from a corpus of documents”

In this section, we will use the information extracted in the previous section using the different text engines to build networks that relate the different information. In particular, we will focus on two kinds of graphs:

  • Knowledge-based graphs, where we will use the semantic meaning of sentences to infer relationships between the different entities.
  • Bipartite graphs, connecting the documents with the entities appearing in the text. We will then project the bipartite graph into a homogeneous graph, which might be made of either document or entity nodes only.

A knowledge graph is a structured representation of entities, their attributes, and relationships, organized as a graph. It encodes semantic relationships to enable reasoning, querying, and knowledge discovery. It is commonly used in AI and machine learning to power applications like recommendation systems, natural language understanding, and data integration. Knowledge graphs are very interesting as they not only relate entities but also provide direction and meaning to the relationship. For instance, take the following relationship:

I - buy -> book

It is substantially different from the following relationship:

I - sell -> book

Besides the kind of relationship (buying or selling), it is also important to have a direction, where the subject and object are not treated symmetrically, but there is a difference between who is performing the action and who is the target of such an action.

In order to create a knowledge graph, we, therefore, need a function that is able to identify for each sentence the subject–verb–object (SVO) triplet. This function can then be applied to all sentences in the corpus and all the triplets can be aggregated to generate the corresponding graph.

The SVO extractor can be implemented on top of the enrichment provided by spacy models. Indeed, the tagging provided by the dependency tree parser can be very helpful to separate main sentences and their subordinates, as well as identifying the SOV triplets. The business logic may need to consider a few special cases (such as conjunctions, negations, and preposition handling) but this can be encoded with a set of rules. Moreover, these rules may also change depending on the specific use case, with slight variations to be tuned by the user.

A base implementation of such rules can be found in https://github.com/NSchrading/intro-spacy-nlp/blob/master/subject_object_extraction.py, which has been slightly adopted for our scope and is included in the GitHub repo provided with this book. Using this helper function, we compute all triplets in the corpus and store them in our corpus DataFrame:

from subject_object_extraction import findSVOs
corpus["triplets"] = corpus["parsed"].apply(
lambda x: findSVOs(x, output="obj")
)
edge_list = pd.DataFrame([
{
"id": _id,
"source": source.lemma_.lower(),
"target": target.lemma_.lower(),
"edge": edge.lemma_.lower()
}
for _id, triplets in corpus["triplets"].items()
for (source, (edge, neg), target) in triplets
# Add stopword filtering
if not any([source.is_stop, target.is_stop])
# Add filtering based on PoS tagging
if (source.pos_ == "PROPN" or source.pos_ == "NOUN")
and (target.pos_== "PROPN" or target.pos_== "NOUN")
])

Note that we have also added stopwords filtering and retention of sources/targets that are nouns (or proper nouns) to only represent relevant edges. Moreover, we reduce the morphological variations of the words using lemmatization.

The type of connection (determined by the sentence main predicate) is stored in the edge column. The first 10 most common relationships can be shown using the following command:

edges["edge"].value_counts().head(10)

The most common edge types correspond to very basic predicates. Indeed, together with very general verbs (such as be, have, tell, and give), we can also find predicates more related to a financial context (such as buy, sell, or make). Using all of these edges, we can now create our knowledge base graph using the networkx utility function:

G = nx.from_pandas_edgelist(
edges, "source", "target",
edge_attr=True, create_using=nx.MultiDiGraph()
)

By filtering the edge DataFrame and creating a subnetwork using this information, we can analyze specific relationship types, such as the lend edge:

G = nx.from_pandas_edgelist(
edges[edges["edge"]=="lend"], "source", "target",
edge_attr=True, create_using=nx.MultiDiGraph()
)

Figure 8.3 shows the subgraph based on the lend relations. As can be seen, it already provides interesting economical insights, such as the economic relationships between countries, such as Venezuela-Ecuador and US-Sudan.

Figure 8.3: Example of a portion of the knowledge graph, for the edges relating to lending relationships

Figure 8.3: Example of a portion of the knowledge graph, for the edges relating to lending relationships

You can indeed play around with the preceding code by filtering the graph based on other relationships, and we definitely encourage you to do so, in order to further unveil interesting insights from the knowledge graphs we just created. In the next section, we will show you another method that allows us to encode the information extracted from the text into a graph structure.

In doing so, we will also make use of a particular type of graph, named bipartite graphs, which we introduced in Chapter 1, Getting Started with Graphs.

Knowledge graphs are rather interesting for unveiling and querying aggregated information over entities. However, other graph representations are also possible and can be useful in other situations. For example, when you want to cluster documents semantically, the knowledge graph may not be the best data structure to be used and analyzed. Knowledge graphs such as the one presented earlier are also not very effective for finding indirect relationships, such as identifying competitors, similar products, and so on, that do not often occur in the same sentence, but that often occur in the same document.

In order to address these limitations, in the next section, we will encode the information present in the document under the form of a bipartite graph.

Bipartite graphs, a special class of graphs as described in Chapter 1, Getting Started with Graphs, are well suited for representing relationships between two distinct sets of entities. Unlike general graphs, where connections can exist between any pair of nodes, bipartite graphs enforce a structure: edges exist only between nodes belonging to different sets. This makes them particularly powerful for modeling systems with naturally dual components, such as users and items in recommendation systems, or, as in our case, documents and entities.

In this section, for each document, we will extract the entities that are most relevant, and connect a node, representing the document, with all the nodes representing the relevant entities in such a document. Each node may have multiple relationships: by definition, each document connects multiple entities. By contract terms, an entity can be referenced in multiple documents. As we will see in the following subsections, multiple cross-referencing in general can be used for creating a measure of similarity between entities and documents. This similarity can also be used to project the bipartite graph into one particular set of nodes, either the document nodes or the entity nodes.

To this aim, in order to build our bipartite graph, we first need to extract the relevant entities of a document. The term relevant entity is clearly fuzzy and broad. In the present context, we will consider as a relevant entity either a named entity (such as organization, person, or location recognized by the NER engine) or a keyword, that is to say, a word (or a composition of words) that identifies and generally describes the document and its content. For instance, suitable keywords for this book may be “graph,” “network,” “machine learning,” “supervised model,” or “unsupervised model.”

There exist many algorithms that extract keywords from a document. One very simple way of doing this is based on the so-called TF-IDF score, which is based on building a score for each token (or group of tokens, often referred to as grams). This score is calculated using two components:

  • Term frequency (TF), which measures the frequency of a word ii in a specific document jj, normalized by the total number of words in the document. This is given by:
TF(i,j)=Term i frequency in document jTotal words in document j\text{TF}(i,j) = \frac{\text{Term } i \text{ frequency in document } j}{\text{Total words in document } j}
  • Inverse document frequency (IDF), which measures how unique a word ii is across the corpus. It is given by:
IDF(i)=log⁡2(Nni)\text{IDF}(i) = \log_2 \left( \frac{N}{n_i} \right)

where NN is the total number of documents, and nin_i is the number of documents containing the word ii.

The TF-IDF score can be computed as:

TF-IDF(i,j)=TF(i,j)×IDF(i)\text{TF-IDF}(i,j) = \text{TF}(i,j) \times \text{IDF}(i)

The TF-IDF score therefore promotes words that are repeated many times in the document and penalizes words that are standard and therefore might not be very representative for a document. There also exist more sophisticated algorithms.

One method that is quite powerful and worth mentioning in the context of this book is TextRank; it is also based on a graph representation of the document. TextRank creates a network where the nodes are a single token (e.g., a word) and where edges are created between tokens that appear within a specified window of one another in the text. Here, “window” refers to a fixed number of consecutive words in the text; if two tokens occur within this range, they are considered connected.

After creating such a network, PageRank is used to compute the centrality for each token, providing a score that allows a ranking within the document based on the centrality score. The most central nodes (up to a certain ratio, generally between 5% and 20% of the document size) are identified as candidate keywords. When two candidate keywords occur close to each other, they get aggregated into composite keywords, made up of multiple tokens. Implementations of TextRank are available in many NLP packages. One such implementation is gensim, which can be used quite straightforwardly:

from gensim.summarization import keywords
text = corpus["clean_text"][0]
keywords(text, words=10, split=True, scores=True,
pos_filter=('NN', 'JJ'), lemmatize=True)

This provides an output of this form:

[('trading', 0.4615130639538529),
('said', 0.3159855693494515),
('export', 0.2691553824958079),
('import', 0.17462010006456888),
('japanese electronics', 0.1360932626379031),
('industry', 0.1286043740379779),
('minister', 0.12229815662000462),
('japan', 0.11434500812642447),
('year', 0.10483992409352465)]

Where the score represents the centrality, representing the importance for a given token. As you can see, some composite tokens may also occur, such as japanese electronics. Keyword extraction can be implemented to compute the keywords for the entire corpus, storing the information in our corpus DataFrame:

corpus["keywords"] = corpus["clean_text"].apply(
lambda text: keywords(
text, words=10, split=True, scores=True,
pos_filter=('NN', 'JJ'), lemmatize=True)
)

To create a bipartite graph using both keywords and named entities as relevant entities, we need to extract named entities and encode the information in a data format that is compatible with our representation of keywords. This can be done using a few utility functions for the following tasks:

  1. Extracting all the entities of a certain type (e.g., location, organization, and person) and filtering by the number of occurrences in the document (to only retain the most relevant entities), returning a pandas DataFrame:

    def extractEntities(ents, minValue=1,
    typeFilters=["GPE", "ORG", "PERSON"]):
    entities = pd.DataFrame([
    {
    "lemma": e.lemma_,
    "lower": e.lemma_.lower(),
    "type": e.label_
    } for e in ents if hasattr(e, "label_")
    ])
    if len(entities)==0:
    return pd.DataFrame()
    g = entities.groupby(["type", "lower"])
    summary = pd.concat({
    "alias": g.apply(lambda x: x["lemma"].unique()),
    "count": g["lower"].count()
    }, axis=1)
    return summary[summary["count"]>1]\
    .loc[pd.IndexSlice[typeFilters, :, :]]
  2. Reparsing the pandas DataFrame to only extract the entities of a given type into a list (empty if there are no entities of that given type):

    def getOrEmpty(parsed, _type):
    try:
    return list(parsed.loc[_type]["count"]\
    .sort_values(ascending=False).to_dict().items())
    except:
    return []
  3. Wrapping up the previous two utilities functions into a more high-level function:

    def toField(ents):
    typeFilters=["GPE", "ORG", "PERSON"]
    parsed = extractEntities(ents, 1, typeFilters)
    return pd.Series({_type: getOrEmpty(parsed, _type)
    for _type in typeFilters})

With these functions, parsing the spacy tags can be simply done with:

entities = corpus["parsed"].apply(lambda x: toField(x.ents))

The entities DataFrame can be easily merged with the corpus DataFrame using the pd.concat function, placing all information in a single data structure:

merged = pd.concat([corpus, entities], axis=1)

Now that we have all the ingredients needed for our bipartite graph, we can create the edge list by looping over all document-entity or document-keyword pairs:

edges = pd.DataFrame([
{"source": _id, "target": keyword, "weight": score, "type": _type}
for _id, row in merged.iterrows()
for _type in ["keywords", "GPE", "ORG", "PERSON"]
for (keyword, score) in row[_type]
])

Once the edge list is created, we can produce the bipartite graph using the networkx APIs:

G = nx.Graph()
G.add_nodes_from(edges["source"].unique(), bipartite=0)
G.add_nodes_from(edges["target"].unique(), bipartite=1)
G.add_edges_from([
(row["source"], row["target"])
for _, row in edges.iterrows()
])

We can now start by looking at an overview of our graph by using nx.info:

Type: Graph
Number of nodes: 25933
Number of edges: 100726
Average degree: 7.7682

Next, we will project the bipartite graph into either of the two sets of nodes: entities or documents. This will allow us to explore the difference between the two graphs we obtain and cluster both the terms and documents using the unsupervised techniques described in Chapter 4, Unsupervised Graph Learning.

We start by projecting our graph into the set of entity nodes. In other words, we create a graph with each node representing an entity or a keyword; in this graph, entities are considered connected if they appear in the same document. networkx provides a special submodule to deal with bipartite graphs, networkx.algorithms.bipartite, where a number of algorithms have already been implemented. In particular, the submodule networkx.algorithms.bipartite.projection provides a number of utility functions to project bipartite graphs on a sub set of nodes.

Before performing the projection, we conveniently categorize the nodes into two distinct sets (either documents or entities), using the “bipartite” property we created when generating the graph:

document_nodes = {n
for n, d in G.nodes(data=True)
if d["bipartite"] == 0}
entity_nodes = {n
for n, d in G.nodes(data=True)
if d["bipartite"] == 1}

The graph projection basically creates a new graph with the set of selected nodes. Edges are places between the nodes depending on whether two nodes have neighbors in common. The basic function projected_graph creates such a network with unweighted edges. However, it is usually more informative to have edges weighted depending on the number of common neighbors or by summing up the weights of all common neighbors. The projection module provides different functions depending on how the weights are computed. In the following subsections, we will use the overlap_weighted_projected_graph, where the edge weight is computed using the Jaccard similarity based on common neighbors. However, we encourage you to also explore the other options, which, depending on your use case and context, may better suit your aims.

Filtering the graph: Be aware of dimensions

Section titled “Filtering the graph: Be aware of dimensions”

A point of caution when dealing with projections: be aware of the dimension of the projected graph. In certain cases, such as the one we are considering here, projection may create extremely large numbers of edges, which makes the graph hard to be analyzed. In our use case, in fact, following the logic we used to create our network, a document node is connected to at least 10 keywords, plus a few entities. In the resulting entity-entity graph, all these entities will be connected with each other, as they share at least one common neighbor (the document that contains them). Therefore, for just one document, we will be generating around O(N2)O(N^2) edges. If we multiply this number by the number of documents, NdN_d, we end up with a number of edges that, despite the small use case, already becomes almost intractable, with a few million edges. Although this surely represents a conservative upper bound (as some of the co-occurrence between entities will be common in many documents and therefore not repeated), it nevertheless provides an order of magnitude of the complexity that you might expect. We, therefore, encourage you to use some caution before projecting your bipartite graph, depending on the topology of the underlying network and the size of your graph. One trick to reduce this complexity and make the projection feasible is to only consider high-degree entity nodes.

Most of the complexity indeed arises from the presence of entities that appear only once or very few times, but still generate cliques within the graph. Such entities are not very informative to capture patterns and provide insights. Besides, they are possibly strongly affected by statistical variability. On the other hand, we should focus on strong correlations that are supported by larger occurrences and provide more reliable statistical results.

We, therefore, only consider high-degree entity nodes. To this aim, we first generate the filtered bipartite subgraph, which excludes nodes with low degree value, namely, smaller than 5:

nodes_with_low_degree = {n
for n, d in nx.degree(G, nbunch=entity_nodes) if d<5}
subGraph = G.subgraph(set(G.nodes) - nodes_with_low_degree)

This subgraph can now be projected without generating a graph with an excessive number of edges:

from networkx.algorithms.bipartite.projection import overlap_weighted_projected_graph
entityGraph = overlap_weighted_projected_graph(
subGraph,
{n for n in subGraph.nodes() if n in entity_nodes}
)

We can check the dimension of the graph with the nx.info networkx function, which gives the following outcome:

Number of nodes: 2378
Number of edges: 120512
Average degree: 101.3558

Despite the filters applied, the number of edges and the average node degree are still quite large. Figure 8.4 shows the distribution of the degree and the edge weights, where we can observe one peak in the degree distribution at fairly low values, with a fat tail toward large degree values. Also, the edge weight shows a similar behavior, with a peak at rather low values and fat right tails. These distributions indeed suggest the presence of a number of small communities, namely cliques, connected to each other via some central nodes.

Figure 8.4: Degree (left) and weight (right) distribution for the entity-entity network

Figure 8.4: Degree (left) and weight (right) distribution for the entity-entity network

The distribution of the edge weights also suggests that a second filter could be applied. The filter on the entity degree that we previously applied on the bipartite graph indeed allowed us to filter out rare entities that appeared on only very few documents. However, the resulting graph could also be affected by an opposite problem: popular entities may be connected just because they tend to appear often in documents, even if there is not an interesting causal connection between them. Consider U.S. and Microsoft. They are almost surely connected, as it is extremely likely that there will be at least one or few documents where they both appear. However, if there is not a strong and causal connection between them, it is very unlikely that the Jaccard similarity will be large. Considering only the edges with the largest weights allow you to focus on the most relevant and possibly stable relations. The edge weight distribution shown in Figure 8.4 suggests that a suitable threshold could be 0.05:

filteredEntityGraph = entityGraph.edge_subgraph(
[edge
for edge in entityGraph.edges
if entityGraph.edges[edge]["weight"]>0.05])

Indeed, such a threshold reduces the number of edges significantly, making the network feasible to be analyzed, as we can see by using nx.info:

Number of nodes: 2265
Number of edges: 8114
Average degree: 7.1647

Figure 8.5: Degree distribution (left) and edge weight distribution (right) for the resulting graph, after the filtering based on the edge weight

Figure 8.5: Degree distribution (left) and edge weight distribution (right) for the resulting graph, after the filtering based on the edge weight

Figure 8.5 shows the distribution of node degree and edge weights for the filtered graph. The distribution for the edge weights corresponds to the right tail of the distribution in Figure 8.4. The relation of degree distribution with Figure 8.4 is less obvious, and it shows a peak of nodes that has a degree around 10, as opposed to the peak seen in Figure 8.4 that was observed in the low range, around 100.

To obtain some further insights on the topology of the network, we also compute its connected components alongside some global measures, such as the average shortest path, clustering coefficient, and global efficiency.

As shown in the previous chapters, the connected components can be obtained using networkx’s utility functions:

components = nx.connected_components(filteredEntityGraph)
pd.Series([len(c) for c in components])

In our analysis, the filtered graph is composed of five different connected components, although the largest one almost entirely accounts for the whole graph (having 2,254 out of 2,265 nodes) with the other connected components being very small.

The graph can also be visualized using Gephi, as shown in the previous chapters:

Figure 8.6: Entity-entity network highlighting the presence of multiple small subcommunities

Figure 8.6: Entity-entity network highlighting the presence of multiple small subcommunities

The global properties of the largest components can be found using the following snippet:

comp = components[0]
global_metrics = pd.Series({
"shortest_path": nx.average_shortest_path_length(comp),
"clustering_coefficient": nx.average_clustering(comp),
"global_efficiency": nx.global_efficiency(comp)
})

Note that the shortest path and global efficiency may require a few minutes of computations. The following results are obtained:

{
'shortest_path': 4.69461456714924,
'clustering_coefficient': 0.2108929012144935,
'global_efficiency': 0.22802077231368997
}

Already from the magnitude of these metrics (shortest path of about 5 and clustering coefficient around 0.2), together with the degree distribution shown above, we can see a general tendency of the network of having multiple communities of limited size. The use of other interesting local properties, such as degree, PageRank, and betweenness centralities distributions, is shown in Figure 8.7, which shows how all these measures tend to correlate and connect to each other. Indeed, as also discussed in Chapter 1, Getting Started with Graphs, the correlation between these measures indicates that, despite the different formulation, they are all relevant quantities to identify “central” nodes: nodes with many neighbors also tend to be highly connected (and highly connect with the various nodes), as well as being the nodes that are most important according to the page rank score.

Figure 8.7: Relations and distribution between degree, page rank, and betweenness centrality measures

Figure 8.7: Relations and distribution between degree, page rank, and betweenness centrality measures

After providing a description in terms of local/ global measures, as well as a general visualization of the network, we will apply some of the techniques we have seen in previous chapters to identify some insights and information within the network, using the unsupervised techniques described in Chapter 4, Unsupervised Graph Learning.

We start by using the Louvain community detection algorithm, which aims at identifying the best partitioning of the nodes into disjointed communities by optimizing the modularity:

import community
communities = community.best_partition(filteredEntityGraph)

Note that the results might vary between runs because of random seeds. However, a similar partition, with a distribution of cluster memberships, to the one shown in Figure 8.8 should emerge. We generally observe around 30 communities, with the larger ones having around 130-150 documents:

Figure 8.8: Distribution of the size of the detected communities

Figure 8.8: Distribution of the size of the detected communities

In Figure 8.9, we show a close-up of one of the communities, where one can identify a particular topic/argument related to the word “turkey”:

Figure 8.9: Close-up for one of the communities identified. In the top image, beside the entity nodes, we also show the document nodes, thus uncovering the structure of the related bipartite graph

Several analyses are possible using the bipartite graph above. For instance, from Figure 8.9 we can uncover a close relationship between Turkey and Greece, which, by filtering the documents based on this relationship, we can discover to be due to some tensions between the two countries because of oil drilling in the Aegean Sea (please also refer to the attached Python notebooks for further information or explore other relationships).

As shown in Chapter 4, Unsupervised Graph Learning, another way of extracting insightful information on the topology and similarities between entities could also be obtained via node embeddings. In particular, we can use node2vec, which, by feeding a randomly generated walk to a skip-gram model, is able to project the nodes into a vector space, where close-by nodes are mapped into nearby points:

from node2vec import Node2Vec
node2vec = Node2Vec(filteredEntityGraph, dimensions=5, num_walks=500)
model = node2vec.fit(window=10)
embeddings = model.wv

In the vector space of embeddings, one could apply traditional clustering algorithms, such as GaussianMixture, K-means, or DBSCAN, for instance. As done in previous chapters, we could also project the embeddings into a 2D plane using t-SNE to visualize clusters and communities. Besides giving another option to identify clusters/communities within the graph, Node2Vec can also be used to also provide similarity between words, as traditionally done by Word2Vec. For instance, we can query the Node2Vec embedding model and find the most similar words to turkey:

[('greek', 0.9906390309333801),
('workers', 0.9882111549377441),
('norwegian', 0.9852849245071411),
('agreed', 0.9809741377830505),
('greece', 0.9735589623451233),
('lme', 0.9709354043006897),
('lira', 0.9682418704032898)]

The words above indeed show the words that are most similar to the “Turkey” entity, measured as the cosine similarity between embedding vectors for various entities based on their “economic” relation derived from the document, for instance, the aforementioned tension between Turkey and Greece that was also highlighted in the community detection above. Although the two approaches, Node2Vec and Word2Vec, indeed share some methodological similarities, the two embedding schemes different type of information: Word2Vec is built directly from the text and encloses relationships at a sentence/syntactic level. Node2Vec, on the other hand, encodes a description that acts more on a document level, derived from the bipartite entity-document graph and its projection on the entity-entity graph used to train the Node2Vec model. As such, the Node2Vec embedding provides a similarity among entities, is inferred from the corpus, and is not based on syntactic references. For instance, the distance between Turkey and Greece may be comparable/similar to the one between any other pair of countries in a Word2Vec embedding, given that the embedding may be able to generally represent the “nation” concept in the embedded space. However, given that Greece and Turkey often appear together in various documents because of the tension in the Aegean Sea, as also shown by the community detection algorithm, the two nations will be closer in a Node2Vec embedding, which encodes the structure of the entity graph.

We will now turn to projecting the bipartite graph into a set of document nodes in order to create a document-document network to be analyzed. In other words, we will create a graph where nodes represent documents and edges represent shared entities or keywords.

In a similar way to as what we did when creating an entity-entity network, we use the overlap_weighted_projected_graph function to obtain a weighted graph that can be filtered to reduce the number of significant edges. Indeed, the topology of the network and the business logic used to build the bipartite graph do not favor clique creation as we have seen with the entity-entity graph: two nodes will be connected only when they share at least one keyword: organization, location, or person. While this connection is certainly possible, it is not very likely within groups of 10-15 nodes, as observed for the entities.

As before, we can easily build our network with the following code:

documentGraph = overlap_weighted_projected_graph(
G,
document_nodes
)

In Figure 8.10, we can inspect the distribution of the degree and the edge weight in order to decide the value of the threshold to be used to filter out edges. Interestingly, the node degree distribution shows a clear peak toward large values as compared to the degree distribution observed for the entity-entity graph. This suggests the presence of several supernodes (a node with a rather large degree and that is highly connected). Also, the edge weight distribution shows the tendency of the Jaccard index to attain values close to 1, thus much larger than the ones observed in the entity-entity graph.

Figure 8.10: Degree and edge weight distribution for the projection of the bipartite graph into the document-document network

Figure 8.10: Degree and edge weight distribution for the projection of the bipartite graph into the document-document network

These two observations highlight a profound difference between the two networks: whereas the entity-entity graph is characterized by a large number of tightly connected communities (namely cliques), the document-document graph is characterized by a core of tightly connected nodes with large degrees and a periphery of weakly connected or disconnected nodes.

It can be convenient to store all the edges in a DataFrame in order to plot them, and later use the DataFrame to filter them to create a subgraph:

allEdgesWeights = pd.Series({
(d[0], d[1]): d[2]["weight"]
for d in documentGraph.edges(data=True)
})

From Figure 8.10, it seems a reasonable choice to set a threshold value for the edge weight of 0.6, which only retains a few thousand edges, therefore allowing us to generate a more tractable network using the networkx function edge_subgraph:

filteredDocumentGraph = documentGraph.edge_subgraph(
allEdgesWeights[(allEdgesWeights>0.6)].index.tolist()
)

Figure 8.11 shows the resulting distribution for the degree and for the edge weight for the reduce graph:

Figure 8.11: Degree and edge weight distribution for the document-document filtered network

Figure 8.11: Degree and edge weight distribution for the document-document filtered network

The substantial difference in topology of the document-document graph with respect to the entity-entity graph can also be clearly seen in Figure 8.12 where we offer you a full network visualization. As anticipated by the distributions, the document-document network is characterized by a core network and a number of weakly connected satellites. The satellites represent all the documents that share no or few keywords or entity common occurrences. The number of disconnected documents is actually quite large and accounts for almost 50% of the total.

Figure 8.12: (Left) Representation of the document-document filtered network, highlighting the presence of a core and a periphery. (Right) Close-up of the core, with some subcommunities embedded. The node size is proportional to the node degree

Figure 8.12: (Left) Representation of the document-document filtered network, highlighting the presence of a core and a periphery. (Right) Close-up of the core, with some subcommunities embedded. The node size is proportional to the node degree

It can be of interest to extract the connected components for this network, using the following commands:

components = pd.Series({
ith: component
for ith, component in enumerate(
nx.connected_components(filteredDocumentGraph)
)
})

In Figure 8.13, we also show the distribution for the connected component sizes, where the presence of a few very large clusters (the cores) can clearly be seen, together with a large number of disconnected or very small components (the periphery or satellites). This structure is strikingly different from the one observed for the entity-entity graph where all nodes generated a very large, connected cluster.

Figure 8.13: Distribution of the connected component sizes, highlighting the presence of many small-size communities (representing the periphery) and a few large communities
(representing the core)

Figure 8.13: Distribution of the connected component sizes, highlighting the presence of many small-size communities (representing the periphery) and a few large communities (representing the core)

It can be interesting to further investigate the structure of the core components. We can extract from the full graph the subgraph composed of the largest components of the network with the following code:

coreDocumentGraph = nx.subgraph(
filteredDocumentGraph,
[node
for nodes in components[components.apply(len)>8].values
for node in nodes]
)

We can inspect the properties of the core network using nx.info, which gives the following output:

Type: Graph
Number of nodes: 1050
Number of edges: 7112
Average degree: 13.5467

The left panel in Figure 8.12 shows a Gephi visualization of the core. As can be seen, the core is composed of few communities, with nodes with fairly large degrees strongly connected to each other.

As done for the entity-entity network, we can process the network to identify communities embedded in the graph. However, differently from before, the document-document graph now provides a means for judging the clustering using the document labels. Indeed, we expect documents belonging to the same topic to be close and connected to each other. Moreover, as we will see, this will also allow us to identify similarities among topics.

First, let us start by extracting the candidate communities:

import community
communities = pd.Series(
community.best_partition(filteredDocumentGraph)
)

Differently from before, the number of detected communities is now very large, around 400, reflecting the core-periphery structure with multiple small communities in the periphery.

We then extract the topic mixture within each community in order to see whether there is homogeneity (all documents belonging to the same class) or some correlation between topics.

We first create a function that returns the number of occurrences for the various topics in a given sub-corpus, represented in a DataFrame, df:

from collections import Counter
def getTopicRatio(df):
return Counter([label
for labels in df["label"]
for label in labels])

We then use this function on each of the communities that the algorithm had extracted:

communityTopics = pd.DataFrame.from_dict({
cid: getTopicRatio(corpus.loc[comm.index])
for cid, comm in communities.groupby(communities)
}, orient="index")

Finally, we normalize the counts to obtain the ratio of topics, summing up to 1:

normalizedCommunityTopics = (
communityTopics.T / communityTopics.sum(axis=1)
).T

Therefore, the normalizedCommunityTopics is a DataFrame that for each community (row in the DataFrame) provides the topic mixture (in percentage) of the different topics (along the column axis). In order to quantify the heterogeneity of the topic mixture within the clusters/communities, we compute the Shannon entropy of each community. Shannon entropy is a measure of diversity in a system, where higher diversity corresponds to greater entropy. It is defined as follows:

H(c)=−∑iP(i∣c)log⁡P(i∣c)H(c) = - \sum_i P(i|c) \log P(i|c)

Where H(c)H(c) represents the entropy of the cluster c and the P(i∣c)P(i|c) corresponds to the percentage of topic i in community c. We compute the empirical Shannon entropy for all communities as follows:

normalizedCommunityTopics.apply(
lambda x: np.sum(-x * np.log(x)), axis=1)

In Figure 8.14, we show the entropy distribution across all communities. Most of communities have zero or very low entropy, thus suggesting that documents belonging to the same class (label) tend to cluster together.

Figure 8.14: Entropy distribution of the topic mixture in each community

Figure 8.14: Entropy distribution of the topic mixture in each community

Even if most of the communities show zero or low variability around topics, it is interesting to investigate whether there exists a relationship between topics, when communities show some heterogeneity. Namely, we compute the correlation between topic distributions:

topicsCorrelation = normalizedCommunityTopics.corr().fillna(0)

They can be represented and visualized using a topic-topic network:

topicsCorrelation[topicsCorrelation<0.8]=0
topicsGraph = nx.from_pandas_adjacency(topicsCorrelation)

In the left panel of Figure 8.15, we show the full graph representation for the topics network. As observed for the document-document network, the topic-topic graph also shows a structure organized in a periphery of disconnected nodes and a strongly connected core. The right panel of Figure 8.15 shows a close-up of the core network that interestingly indicates a correlation that is supported by a semantic meaning with the topics relating to commodities tightly connected to each other.

Figure 8.15: (Left) Topic-topic correlation graph, organized with a periphery-core structure. (Right) Close-up of the core of the network

Figure 8.15: (Left) Topic-topic correlation graph, organized with a periphery-core structure. (Right) Close-up of the core of the network

In this section, we have deeply analyzed the different forms of networks that arise when analyzing documents and, more generally, text sources. In order to do so, we used both global and local properties to statistically describe the networks, as well as some unsupervised algorithms that allowed us to unveil some structure within the graph. In the next section, we will show you how to utilize these graph structures when building a machine learning model.

In order to show you how to utilize the graph structure, we will focus in the following subsections on using the topological information and the connections between entities and documents provided by the bipartite entity-document graph to train multi-label classifiers that are able to predict the document topics.

In order to do this, we will analyze two different approaches:

  • A shallow machine learning approach, where we will use the embeddings extracted from the bipartite network to train traditional classifiers, such as a RandomForest classifier
  • A more integrated and differentiable approach using a graph neural network, which is applied on heterogeneous graphs (such as the bipartite graph)

In the following code block, we will consider the 10 most common topics for which we have enough documents to train and evaluate our models:

from collections import Counter
topics = Counter(
[label
for document_labels in corpus["label"]
for label in document_labels]
).most_common(10)

The preceding code block produces the output shown below, showing the names of the topics that we will focus on in the following analysis:

[('earn', 3964), ('acq', 2369), ('money-fx', 717),
('grain', 582), ('crude', 578), ('trade', 485),
('interest', 478), ('ship', 286), ('wheat', 283),
('corn', 237)]

When training topic classifiers, we will restrict our focus only to those documents that belong to the preceding labels. The filtered corpus can be easily obtained by the following code:

topicsList = [topic[0] for topic in topics]
topicsSet = set(topicsList)
dataset = corpus[corpus["label"].apply(
lambda x: len(topicsSet.intersection(x))>0
)]

Now that we have extracted and structured the dataset, we are ready to start training our topic models and evaluating their performances. In the next subsection, we will start by creating a simple model using shallow-learning methods, and then increase the complexity of the model in the following subsection by using graph neural networks.

We start by implementing a shallow approach for the topic classification tasks, employing the network information. We will show you how to do this, in a step-by-step procedure that you can further customize depending on your use case:

  1. First of all, we start by computing the embeddings using Node2Vec on the bipartite graph. The choice of using the bipartite graph is crucial in order to efficiently utilize the topological information and the connection between entities and documents. In fact, filtered document-document networks are characterized by a periphery with many nodes disconnected, which would not benefit from the topological information. On the other hand, the unfiltered document-document network will have a large number of edges, which makes the scalability of the approach an issue:

    from node2vec import Node2Vec
    node2vec = Node2Vec(G, dimensions=10)
    model = node2vec.fit(window=20)
    embeddings = model.wv

Here, the embedding dimension as well as the window used for generating the walks can be seen as hyper-parameters to be optimized via cross-validation. Some possible choices are 10, 20, and 30 for both variables, although this may vary based on the use case.

  1. In order to make it computationally efficient, a set of embeddings can be computed beforehand, saved to disk, and later used in the optimization. This would work under the assumption that we are in a semi-supervised setting or in a transductive task, where we have all the connection information on the entire dataset, apart from the labels, at training time. Later in this chapter, we will outline another approach, based on the graph neural network, that provides an inductive framework for integrating a topology when training classifiers.

We therefore store the embeddings in a file:

pd.DataFrame(embeddings.vectors,
index=embeddings.index_to_key
).to_pickle(f"graphEmbeddings_{dimension}_{window}.p")

We can choose a different name for each combination of dimension and window.

  1. These embeddings can be simply integrated into a scikit-learn Transformer in order to be used in a grid-search cross-validation:

    from sklearn.base import BaseEstimator
    class EmbeddingsTransformer(BaseEstimator):
    def __init__(self, embeddings_file):
    self.embeddings_file = embeddings_file
    def fit(self, *args, **kwargs):
    self.embeddings = pd.read_pickle(
    self.embeddings_file)
    return self
    def transform(self, X):
    return self.embeddings.loc[X.index]
    def fit_transform(self, X, y=None):
    return self.fit().transform(X)
  2. In order to build a modeling training pipeline, we split our corpus into training and test sets, using the helper function:

    def train_test_split(corpus):
    indices = [index for index in corpus.index]
    train_idx = [idx
    for idx in indices
    if "training/" in idx]
    test_idx = [idx
    for idx in indices
    if "test/" in idx]
    return corpus.loc[train_idx], corpus.loc[test_idx]

We then use the helper function to split the dataset, as follows:

train, test = train_test_split(dataset)
  1. We also build functions to conveniently extract features and labels:

    def get_features(corpus):
    return corpus["parsed"]
    def get_labels(corpus, topicsList=topicsList):
    return corpus["label"].apply(
    lambda labels: pd.Series(
    {label: 1 for label in labels}
    ).reindex(topicsList).fillna(0)
    )[topicsList]
    def get_features_and_labels(corpus):
    return get_features(corpus), get_labels(corpus)
    features, labels = get_features_and_labels(train)
  2. We can now instantiate the modeling pipeline:

    from sklearn.pipeline import Pipeline
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.multioutput import MultiOutputClassifier
    pipeline = Pipeline([
    ("embeddings", EmbeddingsTransformer(
    "my-place-holder")
    ),
    ("model", MultiOutputClassifier(
    RandomForestClassifier())
    )
    ])
  3. We define the parameter space as well as the configuration for the cross-validated grid search:

    from glob import glob
    param_grid = {
    "embeddings__embeddings_file": glob("graphEmbeddings_*"),
    "model__estimator__n_estimators": [50, 100],
    "model__estimator__max_features": [0.2,0.3, "auto"],
    }
    grid_search = GridSearchCV(
    pipeline, param_grid=param_grid, cv=5, n_jobs=-1)
  4. Finally, we train our topic model by using the fit method of the sklearn API:

    model = grid_search.fit(features, labels)

Great! You have just created your topic model that uses the graph information. Once the best model has been identified, we can also use this model on the test dataset to evaluate its performance. In order to do so, we start by defining the following helper function, which allows us to obtain a set of predictions:

def get_predictions(model, features):
return pd.DataFrame(
model.predict(features),
columns=topicsList, index=features.index)
preds = get_predictions(model, get_features(test))
labels = get_labels(test)

Using sklearn ‘s functionalities, we can promptly look at the performances of the trained classifier:

from sklearn.metrics import classification_report
print(classification_report(labels, preds))

The code provides the following output, showing an overall F1-score ranging from 0.6 to 0.8. Such variation may depend on how unbalanced classes are accounted for:

precision recall f1-score support
0 0.97 0.94 0.95 1087
1 0.93 0.74 0.83 719
2 0.79 0.45 0.57 179
3 0.96 0.64 0.77 149
4 0.95 0.59 0.73 189
5 0.95 0.45 0.61 117
6 0.87 0.41 0.56 131
7 0.83 0.21 0.34 89
8 0.69 0.34 0.45 71
9 0.61 0.25 0.35 56
micro avg 0.94 0.72 0.81 2787
macro avg 0.85 0.50 0.62 2787
weighted avg 0.92 0.72 0.79 2787
samples avg 0.76 0.75 0.75 2787

You can play around with the model type and hyper-parameter of the analytical pipeline, by varying the models as well as experimenting with different values to encode the embeddings. As mentioned before, the approach above is clearly transductive, since it uses an embedding trained on the entire dataset. This is a common situation in semi-supervised tasks, where the labeled information is present only in a small subset of points, and the task is to infer the labels for all unknown samples. In the next sub section, we outline how to build an inductive classifier using graph neural networks that can be used when test samples are not known at training time.

We will now describe a neural network-based approach that natively integrates and makes use of the graph structure. Graph neural networks have already been introduced in Chapter 3, Neural Networks and Graphs, and Chapter 4, Unsupervised Graph Learning. However, here we will show you how to apply this framework to heterogeneous graphs, that is, a graph where there is more than one type of node. Each node type might have a different set of features and the training might target only one specific node type over the other.

The approach we present here will make use of stellargraph and the GraphSAGE algorithm, that we have already described previously. A similar example using PyTorch is also available in the GitHub repository (https://github.com/PacktPublishing/Graph-Machine-Learning/blob/main/Chapter08) for interested readers.

More specifically, given that we are dealing with bipartite graphs, we will be using the HinSAGE algorithm, which generalizes the GraphSAGE algorithm from homogeneous graphs (i.e., with only one node type) to heterogenous graphs (i.e., with multiple node types). These methods also support the use of features for each node, instead of just relying on the topology of the graph. If one does not have node features, the one-hot node representation might be used in its place, as also shown in Chapter 7, Social Network Graphs. However, here, in order to make it more general, we will produce a set of node features based on the TF-IDF score (which we saw earlier) for each entity and keyword. Here, we will show you a step-by-step guide to help you train and evaluate a model based on graph neural networks for predicting document topic classification:

  1. We start by computing the TF-IDF score for each document. sklearn already provides some functionalities that allow us to easily compute the TF-IDF scores from a corpus of documents. The sklearn class TfidfVectorizer already comes with a tokenizer embedded. However, since we already have a tokenized and lemmatized version extracted with spacy, we can also provide an implementation of a custom tokenizer that makes use of spacy processing:

    def my_spacy_tokenizer(pos_filter=["NOUN", "VERB", "PROPN"]):
    def tokenizer(doc):
    return [token.lemma_
    for token in doc
    if (pos_filter is None) or
    (token.pos_ in pos_filter)]
    return tokenizer

That can be used in the TfidfVectorizer:

cntVectorizer = TfidfVectorizer(
analyzer=my_spacy_tokenizer(),
max_df = 0.25, min_df = 2, max_features = 10000
)

In order to make the approach truly inductive, the training of the TF-IDF should be done only for the training set and then only applied to the test set:

trainFeatures, trainLabels = get_features_and_labels(train)
testFeatures, testLabels = get_features_and_labels(test)
trainedIDF = cntVectorizer.fit_transform(trainFeatures)
testIDF = cntVectorizer.transform(testFeatures)

For our convenience, the two TF-IDF representations (for the training and test sets) can now be stacked together into a single data structure representing the features for the document nodes for the whole graph:

documentFeatures = pd.concat([pd.DataFrame(trainedIDF.toarray(), index=trainFeatures.index), pd.DataFrame(testIDF.toarray(), index=testFeatures.index)])
  1. Besides the feature information for document nodes, we also build a simple feature vector for entities, based on the one-hot-encoding representation of the entity type:

    entityTypes = {
    entity: ith
    for ith, entity in enumerate(edges["type"].unique())
    }
    entities = edges\
    .groupby(["target", "type"])["source"]\
    .count()\
    .groupby(level=0).apply(
    lambda s: s.droplevel(0)\
    .reindex(entityTypes.keys())\
    .fillna(0))\
    .unstack(level=1)
    entityFeatures = (entities.T / entities.sum(axis=1)).T
  2. We now have all the information to create an instance of a StellarGraph, by merging the information of the node features, both for documents and for entities, with the connections provided by the edges DataFrame. We should only filter out some of the edges/nodes in order to only include the documents belonging to the targeted topics:

    from stellargraph import StellarGraph
    _edges = edges[edges["source"].isin(documentFeatures.index)]
    nodes = {"entity": entityFeatures,
    "document": documentFeatures}
    stellarGraph = StellarGraph(
    nodes, _edges,
    target_column="target", source_column="source", edge_type_column="type"
    )

We have now created our StellarGraph. We can inspect the network similar to how we did for networkx, with:

print(stellarGraph.info())

That provides the following overview:

StellarGraph: Undirected multigraph
Nodes: 23998, Edges: 86849
Node types:
entity: [14964]
Features: float32 vector, length 6
Edge types: entity-GPE->document, entity-ORG->document, entity-PERSON->document, entity-keywords->document
document: [9034]
Features: float32 vector, length 10000
Edge types: document-GPE->entity, document-ORG->entity,
document-PERSON->entity, document-keywords->entity
Edge types:
document-keywords->entity: [78838]
Weights: range=[0.0827011, 1], mean=0.258464,
std=0.0898612
Features: none
document-ORG->entity: [4129]
Weights: range=[2, 22], mean=3.24122, std=2.30508
Features: none
document-GPE->entity: [2943]
Weights: range=[2, 25], mean=3.25926, std=2.07008
Features: none
document-PERSON->entity: [939]
Weights: range=[2, 14], mean=2.97444, std=1.65956
Features: none

The StellarGraph description is actually very informative. Also, StellarGraph handles natively different types of nodes and edges and provides out-of-the-box segmented statistics for each node/edge type.

  1. You may have noticed that the graph we have just created includes both training and test data. In order to truly test the performance of an inductive approach and avoid leakage of information between train and test, we need to create a subgraph with only the data available at training time:

    targets = labels.reindex(documentFeatures.index).fillna(0)
    sampled, hold_out = train_test_split(targets)
    allNeighbors = np.unique([n
    for node in sampled.index
    for n in stellarGraph.neighbors(node)
    ])
    subgraph = stellarGraph.subgraph(
    set(sampled.index).union(allNeighbors)
    )

The considered subgraph has 16,927 nodes and 62,454 edges, as compared to the 23,998 nodes and 86,849 edges of the total graph.

  1. Now that we only have the data and the network available at training time, we can build our machine learning model on top of it. To do so, we first split the data into train, validation, and test data. For training, we will only use 10% of the data, also resembling a semi-supervised task:

    from sklearn.model_selection import train_test_split
    train, leftOut = train_test_split(
    sampled,
    train_size=0.1,
    test_size=None,
    random_state=42
    )
    validation, test = train_test_split(
    leftOut, train_size=0.2, test_size=None, random_state=100,
    )
  2. We can now start to build our graph neural network model using stellargraph and the keras API. First of all, we create a generator able to produce the samples that will feed the neural network. Note that, since we are dealing with a heterogeneous graph, we need a generator that will sample examples from nodes that belongs to a specific class only. In the following code block, we will be using the HinSAGENodeGenerator class, which generalizes the node generator used for homogeneous graphs to heterogeneous graphs, allowing us to specify the node type we want to target:

    from stellargraph.mapper import HinSAGENodeGenerator
    batch_size = 50
    num_samples = [10, 5]
    generator = HinSAGENodeGenerator(
    subgraph, batch_size, num_samples,
    head_node_type="document"
    )

Using this object, we can then create a generator for the train and validation datasets:

train_gen = generator.flow(train.index, train, shuffle=True)
val_gen = generator.flow(validation.index, validation)
  1. We can now create our GraphSAGE model. As already done for the generator, also in this case, we need to use a model that is able to handle heterogenous graph. HinSAGE will be used in place of GraphSAGE:

    from stellargraph.layer import HinSAGE
    from tensorflow.keras import layers
    graphsage_model = HinSAGE(
    layer_sizes=[32, 32], generator=generator,
    bias=True, dropout=0.5
    )
    x_inp, x_out = graphsage_model.in_out_tensors()
    prediction = layers.Dense(
    units=train.shape[1], activation="sigmoid"
    )(x_out)

Note that in the final dense layer, we use a sigmoid activation function instead of softmax, since the problem at hand is a multi-class, multi-label task. Softmax would in fact normalize all scores to sum to 1, and it is therefore more suited to single-label classification. On the other hand, given that a document may belong to more than one class, the sigmoid activation function is a more sensible choice in this context. As usual, we compile our Keras model:

from tensorflow.keras import optimizers, losses, Model
model = Model(inputs=x_inp, outputs=prediction)
model.compile(
optimizer=optimizers.Adam(learning_rate=0.005),
loss=losses.binary_crossentropy,
metrics=["acc"]
)
  1. Finally, we train the neural network model with:

    history = model.fit(
    train_gen, epochs=50, validation_data=val_gen,
    verbose=1, shuffle=False
    )

Figure 8.16: (Top) Train and validation accuracy versus the number of epochs.
(Bottom) Binary cross-entropy loss for the training and validation dataset versus the number of epochs

Figure 8.16: (Top) Train and validation accuracy versus the number of epochs. (Bottom) Binary cross-entropy loss for the training and validation dataset versus the number of epochs

Figure 8.16 shows the plots of the evolution for the train and validation losses and accuracy versus the number of epochs. As the figure shows, train and validation accuracy increase consistently up to around 30 epochs. After the accuracy on the validation set settles to a plateau, whereas training accuracy continues to increase, indicating a tendency to slight overfitting. Thus, stopping training in the range between 30 and 50 seems a rather legitimate choice.

  1. Once the model is trained, we can test its performance on the test set:

    test_gen = generator.flow(test.index, test)
    test_metrics = model.evaluate(test_gen)

This should provide the following values:

loss: 0.0933
accuracy: 0.8795

Note that because of the unbalanced label distribution, accuracy may not be the best choice for assessing performances. Besides, the value of 0.5 generally used for thresholding and providing label assignment may also be sub-optimal in unbalanced settings.

  1. To identify the best threshold to be used to classify the documents, we first compute the topic assignment probabilities predicted by the model over all the test samples:

    test_predictions = pd.DataFrame(
    model.predict(test_gen), index=test.index,
    columns=test.columns)
    test_results = pd.concat({
    "target": test,
    "preds": test_predictions
    }, axis=1)

We then compute the F1-score with a macro average (where the F1-score for the individual classes are averaged) for different threshold choices:

thresholds = [0.01,0.05,0.1,0.2,0.3,0.4,0.5]
f1s = {}
for th in thresholds:
y_true = test_results["target"]
y_pred = 1.0*(test_results["preds"]>th)
f1s[th] = f1_score(y_true, y_pred, average="macro")
pd.Series(f1s).plot()

As shown in Figure 8.17, a threshold value of 0.2 seems to be the best choice that achieves the best performance:

Figure 8.17: Macro-averaged F1-score versus the threshold used for labeling

Figure 8.17: Macro-averaged F1-score versus the threshold used for labeling

  1. Using the threshold value of 0.2, we can finally extract the classification report on the test set:

    print(classification_report(
    test_results["target"], 1.0*(test_results["preds"]>0.2))
    )

This gives the following output:

precision recall f1-score support
0 0.92 0.97 0.94 2075
1 0.85 0.96 0.90 1200
2 0.65 0.90 0.75 364
3 0.83 0.95 0.89 305
4 0.86 0.68 0.76 296
5 0.74 0.56 0.63 269
6 0.60 0.80 0.69 245
7 0.62 0.10 0.17 150
8 0.49 0.95 0.65 149
9 0.44 0.88 0.58 129
micro avg 0.80 0.89 0.84 5182
macro avg 0.70 0.78 0.70 5182
weighted avg 0.82 0.89 0.84 5182
samples avg 0.83 0.90 0.85 5182
  1. At this point, we have trained a graph neural network model and assessed its performance. We now aim to apply this model on a set of unobserved data—the data that was left out at the very beginning—and represent the true test data in an inductive setting. We therefore need to instantiate a new generator:

    generator = HinSAGENodeGenerator(
    stellarGraph, batch_size, num_samples,
    head_node_type="document")

Note that the graph taken as an input of the HinSAGENodeGenerator is now the entire graph (in place of the filtered one used before), with both training and test documents. Using this class, we can create a generator that samples from the test nodes only, filtering out the ones that do not belong to one of our main, selected topics:

hold_out = hold_out[hold_out.sum(axis=1) > 0]
hold_out_gen = generator.flow(hold_out.index, hold_out)
  1. The model can then be evaluated over these samples and labels are predicted using the threshold identified earlier of 0.2:

    hold_out_predictions = model.predict(hold_out_gen)
    preds = pd.DataFrame(1.0*(hold_out_predictions > 0.2),
    index = hold_out.index,
    columns = hold_out.columns)
    results = pd.concat(
    {"target": hold_out,"preds": preds}, axis=1
    )

We can finally extract the performance on the inductive test dataset:

print(classification_report(
results["target"], results["preds"])
)

This provides the following table:

precision recall f1-score support
0 0.93 0.99 0.96 1087
1 0.90 0.97 0.93 719
2 0.64 0.92 0.76 179
3 0.82 0.95 0.88 149
4 0.85 0.62 0.72 189
5 0.74 0.50 0.59 117
6 0.60 0.79 0.68 131
7 0.43 0.03 0.06 89
8 0.50 0.96 0.66 71
9 0.39 0.86 0.54 56
micro avg 0.82 0.89 0.85 2787
macro avg 0.68 0.76 0.68 2787
weighted avg 0.83 0.89 0.84 2787
samples avg 0.84 0.90 0.86 2787

As compared to the shallow-learning method, we can see that we have achieved a substantial improvement in performance, between 5 and 10%.

In this chapter, you have learned how to process unstructured information and how to represent such information by means of a graph. Starting from a well-known benchmark dataset, Reuters-21578, we applied standard NLP engines to tag and structure textual information. These high-level features were then used to create different types of networks: knowledge base networks, bipartite networks, projections of bipartite networks onto each subset of node types, and a topic-topic similarity network. The different graphs also allowed us to use the tools we have presented in previous chapters to extract insights from the network representation.

We used local and global properties in order to show you how these quantities can represent and describe structurally different types of networks. Unsupervised techniques were then used in order to identify semantic communities and cluster together documents belonging to similar subjects/topics. Finally, we used the labeled information provided in the dataset to train supervised multi-class multi-label classifiers, which also utilized the topology of the network.

In particular, we applied supervised techniques to the case of a heterogeneous graph, where two different node types are present: documents and entities. In this setting, we showed you how to implement both transductive and inductive approaches using shallow learning and graph neural networks, respectively.

In the next chapter, we will turn to another domain where graph analytics can be efficiently used to extract insights and/or create machine learning models that leverage network topology: transactional data. The use case we look at in the next chapter will also allow you to take the bipartite graph concepts introduced in this chapter to another level: tripartite graphs.