Join us
@takhan ă» Jul 02,2022 ă» 5 min read ă» 1398 views
In this article we will introduce techniques for organizing text data. We will see how we can analyze a large corpus of text data present in the form of text documents and extract feature vectors for individual documents, in order to be able to retrieve documents with similar content.
In this article we will introduce techniques for organizing text data. We will see how we can analyze a large corpus of text data present in the form of text documents and extract feature vectors for individual documents, in order to be able to retrieve documents with similar content.
The term Text retrieval can be stated as the matching of some user generated query against a set of text records. These records could be of any type such as: unstructured text, documentations, textual-reports, newspaper articles, paragraphs in a manual, etc. User queries can range from multi-sentence full descriptions or to just a few words. Text retrieval is a subset of Information retrieval systems. Search engines like Google, Bing, etc. are example of such systems.
Python and Scikit-learn, Scipy packages are required to run through this article, as well as a corpus of text documents. This code can be adapted to work with other set of documents we collect.
We will use the well-known Reuters-21578 dataset. It includes 12,902 documents for 90 classes, with a fixed splitting between test and training data (3,299, 9,603). The dataset can be downloaded from (http://disi.unitn.it/moschitti/corpora.htm) for âReuters21578-Apte-90Catâ category.
Once we have downloaded and unzipped the dataset, we can take a look inside the folder. It is split into two folders, âtrainingâ and âtestâ. Each of those contains 91 subfolders, corresponding to pre-labeled categories, which will be useful for us later when we want to try classifying the category of an unknown message. In this article, we are not worried about training a classifier, so weâll end up using both sets together.
In this section we will perform data exploration, data pre-processing, text-vectorization, and text-analysis steps.
Letâs open up a single message and look at the contents. This is the very first message in the training folder, inside of the âacqâ folder, which is a category apparently containing news of corporate acquisitions.
Figure below shows a single sample message.
Our collection contains over 15,000 articles with a lot of information. It would take way too long to get through all the information.
Figure below shows the different groups present in our dataset.
Letâs load all of our documents (news articles) into a single list called docs. Weâll iterate through each group, grab all of the posts in each group (from both training and test directories), and add the text of the post into the docs list. We will make sure to exclude duplicate posts by cheking if weâve seen the post index before.
Figure below shows the output of above code and content of document number 100.
We will now use sklearnâs Tf-idfVectorizer to compute the tf-idf matrix of our collection of documents. The tf-idf matrix is an n*m matrix with the ânâ rows corresponding to our ânâ documents and the âmâ columns corresponding to our terms.
The values corresponds to the âimportanceâ of each term to each document, where importance is *. In this case, terms are just all the unique words in the corpus, minus english âstopwordsâ, which are the most common words in the english language, e.g. âitâ, âtheyâ, âandâ, âaâ, etc. In some cases, terms can be n-grams (n-length sequences of words) or more complex, but usually just words.
To compute the tf-idf matrix, run:
We see that the variable tf-idf is a sparse matrix with a row for each document, and a column for each unique term in the corpus.
Thus, we can interpret each row of this matrix as a feature vector which describes a document. Two documents which have identical rows have the same collection of words in them, although not necessarily in the same order; word order is not preserved in the tf-idf matrix. Regardless, it seems reasonable to expect that if two documents have similar or close tf-idf vectors, they probably have similar content.
In practice however, the term-document matrix alone has several disadvantages. For one, it is very high-dimensional and sparse (mostly zeroes), thus it is computationally costly.
Additionally, it ignores similarity among groups of terms. For example, the words âseatâ and âchairâ are related, but in a raw term-document matrix they are separate columns. So two sentences with one of each word will not be computed as similarly.
One solution is to use latent semantic analysis (LSA, or sometimes called latent semantic indexing). LSA is a dimensionality reduction technique closely related to principal component analysis, which is commonly used to reduce a high-dimensional set of terms into a lower-dimensional set of âconceptsâ or components which are linear combinations of the terms.
To do so, we use sklearnâs âTruncatedSVDâ function which gives us the LSA by computing a singular value decomposition (SVD) of the tf-idf matrix.
How to interpret this? âlsaâ holds our latent semantic analysis, expressing our 100 concepts. It has a vector for each concept, which holds the weight of each term to that concept. âtfidf_lsaâ is our transformed document matrix where each document is a weighted sum of the concepts.
In a simpler analysis with, for example, two topics (sports and tacos), one concept might assign high weights for sports-related terms (ball, score, tournament) and the other one might have high weights for taco-related concepts (cheese, tomato, lettuce). In a more complex one like this one, the concepts may not be as interpretable. Nevertheless, we can investigate the weights for each concept, and look at the top-weighted ones. For example, below here are the top terms in concept 1.
The top terms in concept 1 appear related to accounting balance sheets; terms like ânetâ, âlossâ, âprofitâ.
Now, back to our documents. Recall that tfidf_lsa is a transformation of our original tf-idf matrix from the term-space into a concept-space. The concept space is much more valuable, and we can use it to query most similar documents. We expect that two documents which about similar things should have similar vectors in tfidf_lsa. We can use a simple distance metric to measure the similarity, euclidean distance or cosine similarity being the two most common.
Here, weâll select a single query document (index 300), calculate the distance of every other document to our query document, and take the one with the smallest distance to the query.
Figure below shows the Query document.
Figure below shows the most similar document obtained in response to the query.
Interesting find! Our query document appears to be about buying a stake. Our return document is a related article about the same topic. Try looking at the next few closest results. A quick inspection reveals that most of them are about the same story.
Thus we see the value of this procedure. It gives us a way to quickly identify articles which are related to each other. This can greatly aid journalists who have to sift through a lot of content that is not always indexed or organized.
Complete code can be found at (https://github.com/tkhan11/NLP-based-Text-Retrieval).
Join other developers and claim your FAUN account now!
Research Scholar, Jamia Millia Islamia
@takhanInfluence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.