Natural Language Processing (NLP) in JavaScript (series 2)
Tags: javascript, ai, machinelearning, nlp
Published: 2023-07-19 05:56:16

<p data-pm-slice="1 3 []">Natural Language Processing (NLP) is a field of artificial intelligence that focuses on enabling computers to understand, interpret, and generate human language.</p>
It plays a critical role in modern applications, ranging from language translation and sentiment analysis to chatbots and search engines.

NLP techniques empower developers to extract insights from vast amounts of textual data, making it a powerful tool for data analysis and decision-making.

In the first part of this article, we learned how to set up an environment and gather data, strip them of irrelevant words while preparing the data to be used as samples.

In the following session, we would see how to use the data. Find the previous session <a class="attrlink" href="https://blog.learnhub.africa/2023/07/18/natural-language-processing-nlp-in-javascript-series/" target="_blank" rel="noopener noreferrer nofollow">here</a>.
<h3>Part-of-Speech (POS) Tagging in JavaScript</h3>
In Natural Language Processing (NLP), Part-of-Speech (POS) tagging is a crucial task that involves assigning specific parts of speech, such as nouns, verbs, adjectives, and more, to each word in a sentence.

<strong>Understanding Part-of-Speech Tagging</strong>

POS tagging plays a vital role in NLP, as it helps in understanding the grammatical structure of a sentence, which is essential for various language-related tasks.

The process involves analyzing each word in a sentence and assigning them their corresponding part of speech. For example, in the sentence "The quick brown fox jumps over the lazy dog," the words would be tagged as follows:
<ul>
 	<li>"The" -&gt; Determiner (DT)</li>
 	<li>"quick" -&gt; Adjective (JJ)</li>
 	<li>"brown" -&gt; Adjective (JJ)</li>
 	<li>"fox" -&gt; Noun (NN)</li>
 	<li>"jumps" -&gt; Verb (VBZ)</li>
 	<li>"over" -&gt; Preposition (IN)</li>
 	<li>"the" -&gt; Determiner (DT)</li>
 	<li>"lazy" -&gt; Adjective (JJ)</li>
 	<li>"dog" -&gt; Noun (NN)</li>
</ul>
<strong>Working with POS Tagging in JavaScript</strong>

We'll use the "natural" <a class="attrlink" href="https://github.com/axa-group/nlp.js" target="_blank" rel="noopener noreferrer nofollow">NLP library</a>; follow the <a class="attrlink" href="https://blog.learnhub.africa/2023/07/18/natural-language-processing-nlp-in-javascript-series/" target="_blank" rel="noopener noreferrer nofollow">previous session</a> to understand how to set up your environment.

To perform POS tagging in JavaScript, which supports various NLP tasks, including tokenization, POS tagging, and more.

<strong>Implementing POS Tagging</strong>

To implement this step, you must set up the "natural" library, and the steps are outlined in the first session of this two-part series. Let's implement POS tagging in JavaScript.
```javascript
// Import the "natural" library
const natural = require('natural');

// Create a tokenizer and POS tagger instance
const tokenizer = new natural.WordTokenizer();
const posTagger = new natural.BrillPOSTagger(
  natural.BrillPOSTagger.defaultRules,
  natural.BrillPOSTagger.defaultLexicon
);

// Sample sentence for POS tagging
const sentence = "The quick brown fox jumps over the lazy dog";

// Tokenize the sentence into words
const words = tokenizer.tokenize(sentence);

// Perform POS tagging
const taggedWords = posTagger.tag(words);

// Print the tagged words
taggedWords.forEach((word) =&gt; {
  console.log(`${word[0]} - ${word[1]}`);
});
```
<strong>Explanation</strong>
<ul>
 	<li>We import the "natural" library and create instances for tokenization and POS tagging using <strong>natural.WordTokenizer()</strong> and <strong>natural.BrillPOSTagger()</strong>.</li>
 	<li>We define a sample sentence we want to tag with parts of speech.</li>
 	<li>The sentence is tokenized into individual words using the <strong>tokenizer.tokenize()</strong> function.</li>
 	<li>The <strong>posTagger.tag()</strong> function performs POS tagging on the tokenized words.</li>
 	<li>Finally, we iterate through the tagged words and print them along with their respective parts of speech.</li>
</ul>
<h3>Topic Modeling in JavaScript</h3>
Topic modeling is an unsupervised learning technique used to discover underlying themes or topics within a collection of text documents.  We'll use a sample corpus of documents to extract meaningful topics.

<strong>Understanding Topic Modeling</strong>

Topic modeling is a statistical approach aiming to uncover latent topics in a large set of text documents.

It enables us to identify the main themes or subjects without any prior labeling or human supervision.

One of the popular algorithms for topic modeling is Latent Dirichlet Allocation (LDA).

LDA assumes that each document in the corpus is a mixture of various topics, and a distribution of words represents each topic.

The algorithm then works iteratively to assign words to different topics and determine the probability of each topic's presence in a given document.

By the end of the process, we get a list of topics and the words that contribute most to each topic.

<strong>Working with Topic Modeling in JavaScript</strong>

We will utilize the "natural" NLP library to perform topic modeling in JavaScript. We'll use a sample corpus of documents to demonstrate the process.

<strong>Implementing Topic Modeling</strong>
```javascript
// Import the "natural" library
const natural = require('natural');

// Create a new LDA instance
const lda = new natural.LdaSandbox();

// Sample corpus of documents
const documents = [
  "Machine learning is an exciting field in computer science.",
  "JavaScript is a versatile programming language used for web development.",
  "Data science involves extracting insights from data using various techniques.",
  "Node.js is a popular runtime environment for server-side JavaScript applications.",
  "Topic modeling helps in discovering latent themes from text documents.",
];

// Tokenize the documents
const tokenizer = new natural.WordTokenizer();
const tokenizedDocs = documents.map((doc) =&gt; tokenizer.tokenize(doc));

// Perform topic modeling
const numTopics = 2; // Set the number of topics to discover
const numIterations = 1000; // Number of iterations for the algorithm
lda.train(tokenizedDocs, numTopics, numIterations);

// Print the extracted topics
const topics = lda.getTopics();
console.log("Extracted Topics:");
topics.forEach((topic, index) =&gt; {
  console.log(`Topic ${index + 1}: ${topic.words.join(", ")}`);
});
```
<strong>Explanation</strong>
<ul>
 	<li>We import the "natural" library, allowing us to work with topic modeling.</li>
 	<li>A sample corpus of documents is defined, representing the collection of text we want to analyze and extract topics from.</li>
 	<li>The documents are tokenized into individual words using the <strong>natural.WordTokenizer()</strong>.</li>
 	<li>We set the number of topics (<strong>numTopics</strong>) we want the algorithm to discover and the number of iterations (<strong>numIterations</strong>) for the LDA algorithm to converge.</li>
 	<li>The <strong>lda.train()</strong> function performs topic modeling on the tokenized documents.</li>
 	<li>Finally, we retrieve and print the extracted topics and the most representative words for each topic using the <strong>lda.getTopics()</strong> function.</li>
</ul>
Session 8: Text Classification with NLP

Text classification is a vital Natural Language Processing (NLP) task that involves categorizing textual data into predefined classes or categories.

<strong>Understanding Text Classification</strong>

Text classification is crucial in various real-world applications, including sentiment analysis, spam detection, language identification, and content categorization. The goal is automatically assigning a label or category to a given text document based on its content.

To achieve text classification, we can leverage machine learning algorithms that learn patterns and relationships between the textual data and their corresponding classes.

One commonly used text classification algorithm is the Naive Bayes classifier, which is simple yet effective for many NLP tasks.

<strong>Implementing Text Classification</strong>
```javascript
// Import the "natural" library
const natural = require('natural');

// Create a new Naive Bayes classifier instance
const classifier = new natural.BayesClassifier();

// Training data for text classification
const trainingData = [
  { text: "I love this product! It's fantastic.", category: "positive" },
  { text: "This movie was boring and disappointing.", category: "negative" },
  { text: "The weather is lovely today.", category: "positive" },
  { text: "The service at this restaurant was terrible.", category: "negative" },
  { text: "The new software update works perfectly.", category: "positive" },
];

// Training the classifier with the data
trainingData.forEach((data) =&gt; {
  classifier.addDocument(data.text, data.category);
});
classifier.train();

// Test data for text classification
const testText = "The hotel stay was wonderful! I had a great time.";

// Classify the test data
const predictedCategory = classifier.classify(testText);

// Print the predicted category
console.log(`Predicted Category: ${predictedCategory}`);
```
<strong>Explanation</strong>
<ul>
 	<li>We import the "natural" library, which provides the necessary tools for text classification.</li>
 	<li>We create a new instance of the Naive Bayes classifier using <strong>natural.BayesClassifier()</strong>.</li>
 	<li>The training data contains labeled examples of text and corresponding categories (positive or negative in this case).</li>
 	<li>The classifier is trained on the training data using the <strong>classifier.addDocument()</strong> and <strong>classifier.train()</strong> functions.</li>
 	<li>We define a test text for which we want to predict the category.</li>
 	<li>The <strong>classifier.classify()</strong> function is used to classify the test text into a specific category.</li>
 	<li>The predicted category is printed on the console.</li>
</ul>
<h3>Language Translation with NLP in JavaScript</h3>
Language translation is a crucial NLP application that enables communication and understanding across different languages. This session focuses on language translation techniques and demonstrates how to perform language translation in JavaScript using NLP libraries.

<strong>Language Translation Techniques</strong>

Language translation can be achieved using different techniques, including rule-based approaches, statistical machine translation, and neural machine translation. In this session, we'll utilize the power of NLP libraries to perform language translation.

<strong>Implementing Language Translation in JavaScript</strong>

To perform language translation in JavaScript, we can leverage NLP libraries such as "translate-google" and "translate" to access translation services.

<strong>Example: Translating Text Using "translate-google" Library</strong>
```javascript
// Import the "translate-google" library
const translate = require('translate-google');

// Text to be translated
const text = "Hello, how are you?";

// Source and target languages
const sourceLanguage = 'en';
const targetLanguage = 'es';

// Translate the text
translate(text, { from: sourceLanguage, to: targetLanguage })
  .then((translation) =&gt; {
    console.log(`Translated Text: ${translation}`);
  })
  .catch((error) =&gt; {
    console.error('Translation Error:', error);
  });
```
<strong>Example: Translating Text Using "translate" Library</strong>
```javascript
// Import the "translate" library
const translate = require('translate');

// Configure the library with the translation service
translate.engine = 'google';
translate.from = 'en';
translate.to = 'fr';

// Text to be translated
const text = "Good morning, how are you today?";

// Translate the text
translate(text)
  .then((translation) =&gt; {
    console.log(`Translated Text: ${translation}`);
  })
  .catch((error) =&gt; {
    console.error('Translation Error:', error);
  });
```
<strong>Explanation</strong>
<ul>
 	<li>We import the required NLP libraries for language translation: "translate-google" or "translate".</li>
 	<li>We define the text that needs to be translated.</li>
 	<li>We specify the source language (<strong>sourceLanguage</strong>) and the target language (<strong>targetLanguage</strong>) for translation.</li>
 	<li>The text is translated using the <strong>translate()</strong> function provided by the respective library.</li>
 	<li>The translated text is printed to the console.</li>
</ul>
In the final session of this series, we would look at the use case and future trend of NLP and how its implication in Javascript has the potential to transform learning.

Follow us to see how we build the final project, as this is the first session of a three-part series. If you find this post exciting, find more exciting posts on <a class="attrlink" href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Learnhub Blog</a>; we write everything tech from <a class="attrlink" href="https://blog.learnhub.africa/category/cloud-computing/" target="_blank" rel="noopener noreferrer nofollow">Cloud computing</a> to <a class="attrlink" href="https://blog.learnhub.africa/category/frontend/" target="_blank" rel="noopener noreferrer nofollow">Frontend Dev</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/security/" target="_blank" rel="noopener noreferrer nofollow">Cybersecurity</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/data-science/" target="_blank" rel="noopener noreferrer nofollow">AI</a>, and <a class="attrlink" href="https://blog.learnhub.africa/category/blockchain/" target="_blank" rel="noopener noreferrer nofollow">Blockchain</a>.
<h3>Resource</h3>
<ul>
 	<li><a class="attrlink" href="https://www.codecademy.com/learn/learn-how-to-code?periods=year&amp;plan_id=proGoldAnnualV2&amp;utm_source=pepperjam&amp;utm_medium=affiliate&amp;utm_term=96525&amp;clickId=4438617034&amp;pj_creativeid=8-12462&amp;pj_publisherid=96525" target="_blank" rel="noopener noreferrer nofollow">Getting Started with Programming</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/06/08/4-javascript-email-frameworks-nodemailer-sendgrid-smtp-js-and-mailgun/" target="_blank" rel="noopener noreferrer nofollow">Javascript Email with Nodemailer</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/01/18/how-to-send-an-email-in-node-js-using-nodemailer/" target="_blank" rel="noopener noreferrer nofollow">How to send an email in node.js using nodemailer</a></li>
 	<li><a class="attrlink" href="https://www.w3schools.com/js/js_arrays.asp" target="_blank" rel="noopener noreferrer nofollow">Javascript Array method</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/09/20-best-javascript-frameworks-for-2023/" target="_blank" rel="noopener noreferrer nofollow">20 Best React JavaScript Frameworks For 2023</a></li>
</ul>