NLP Module - 1 PDF
NLP Module - 1 PDF
The field of NLP involves making computers to perform useful tasks with the natural languages humans use. The
input and output of an NLP system can be
• Speech
• Written Text
NLP trinity:
1. Sentiment analysis:
• Sentiment analysis, also referred to as opinion mining - identifies the emotional tone behind a body of
text.
• Helps organizations gather insights into real-time customer sentiment, customer experience and brand
reputation.
• Use text analytics to analyze online sources such as emails, blog posts, online reviews, news articles,
survey responses, case studies, web chats, tweets, forums and comments.
U20CSST01 - NATURAL LANGUAGE PROCESSING
• The metrics used are designed to detect whether the overall sentiment of a piece of text is positive,
negative or neutral.
2. Machine Translation :
• Sub-field of computational linguistics that investigates the use of software to translate text or speech
from one language to another.
• Corpus: A collection of written texts, especially the entire works of a particular author.
3. Text Extraction :
• Extract information from text or unstructured data.
• Extract information such as entity names, locations, quantities, and more.
4. Text Classification :
• Unstructured text - hard to extract value from this data unless it’s organized.
• Text classification also known as text tagging or text categorization is the process of categorizing text
into organized groups.
• Text classifiers can automatically analyze text and then assign a set of pre-defined tags or categories
based on its content.
5. Speech Recognition :
• An interdisciplinary subfield of computer science and computational linguistics that develops
methodologies and technologies that enable the recognition and translation of spoken language into text
by computers.
• Automatic speech recognition (ASR), computer speech recognition or speech to text (STT).
6. Chatbot :
• Computer programs that conduct automatic conversations with people. They are mainly used in
customer service for information acquisition.
7. Email Filter :
• Most fundamental and essential applications of NLP.
• It began with spam filters, which identified specific words or phrases that indicate a spam message.
But, like early NLP adaptations, filtering has been improved.
Components of NLP :
• There are two components of NLP as given –
➢ Natural Language Understanding (NLU)
➢ Natural Language Generation (NLG)
• Natural Language Understanding (NLU) :
Understanding involves the following tasks –
✓ Mapping the given input in natural language into useful representations.
✓ Analyzing different aspects of the language.
• Natural Language Generation (NLG):
It is the process of producing meaningful phrases and sentences in the form of natural language from
some internal representation.
It involves –
✓ Text planning − It includes retrieving the relevant content from knowledge base.
✓ Sentence planning − It includes choosing required words, forming meaningful
phrases, setting tone of the sentence.
✓ Text Realization − It is mapping sentence plan into sentence structure.
U20CSST01 - NATURAL LANGUAGE PROCESSING
NLP Terminology:
• Discourse : It deals with how the immediately preceding sentence can affect the interpretation of the
next sentence.
Steps/Stages in NLP :
Lexical Analysis :
• Lexical analysis is the process of converting a sequence of characters into a sequence of tokens.
A lexer is generally combined with a parser, which together analyzes the syntax of
programming languages, web pages, and so forth.
• Lexers and parsers are most often used for compilers but can be used for other computer
languages tools, such as pretty printers or liters.
• Lexical analysis is also an important analysis during the early stage of natural language
processing, where text or sound waves are segmented into words and other units
• Lexeme: A lexeme is a basic unit of meaning. In linguistics, the abstract unit of morphological
analysis that corresponds to a set of forms taken by a single word is called lexeme.
U20CSST01 - NATURAL LANGUAGE PROCESSING
Syntactic Analysis :
• Parsing, syntax analysis, or syntactic analysis is the process of analyzing a string of symbols,
either in natural language, computer languages, or data structures, conforming to the rules of
formal grammar.
• It is used in the analysis of computer languages, referring to the syntactic analysis of the input
code into its component parts to facilitate the writing of compilers and interpreters.
• Grammatical rules are applied to categories and groups of words, not individual words.
Syntactic analysis is a very important part of NLP that helps in understanding the grammatical
meaning of any sentence.
Semantic Analysis :
• Semantic Analysis attempts to understand the meaning of Natural Language.
• Semantic Analysis of Natural Language captures the meaning of the given text while
considering context, logical structuring of sentences, and grammar roles.
• 2 parts of Semantic Analysis are (a) Lexical Semantic Analysis and (b) Compositional
Semantics Analysis. Semantic analysis can begin with the relationship between individual
words.
Discourse Integration:
• Researchers use Discourse analysis to uncover the motivation behind a text.
• It is useful for studying the underlying meaning of a spoken or written text as it considers the
social and historical contexts.
• Discourse analysis is a process of performing text or language analysis, involving text
interpretation, and understanding social interactions.
Pragmatic Analysis
• Pragmatic Analysis is part of the process of extracting information from text. It focuses on
taking a structured set of text and figuring out the actual meaning of the text.
• It also focuses on the meaning of the words of the time and context. Effects on interpretation
can be measured using PA by understanding the communicative and social content
NLP PIPELINE:
NLP is a set of steps followed to build an end-to-end NLP software. In simple terms, To create a complete NLP
software, we follow a series of steps and that is called the NLP pipeline.
1. Data Acquisition
2. Text Preprocessing
3. Feature Engineering
4. Modelling
5. Evaluation
6. Deployment
U20CSST01 - NATURAL LANGUAGE PROCESSING
1. Data Acquisition :
• Data acquisition involves obtaining raw textual data from various sources to create a robust dataset for
NLP tasks.
• Data acquisition- face one of three situations:
1. Data on Your Desk: The data needed for the NLP task is already in possession. Initiate the text
preprocessing stage immediately.
2. Data in Databases: The required data resides within company databases or repositories.
Collaborate with data engineers to retrieve the data.
3. Less Data: Insufficient data volume for robust model training or analysis. Employ data
augmentation techniques to enhance the dataset.
(ii) Data from Other Resources
• Public Datasets: Utilize publicly available datasets from repositories like Kaggle, UCI
Machine Learning Repository, or government databases, aligning them with the project’s
requirements.
• Web Scraping: Extract data from websites or forums by scraping relevant information. Tools
like BeautifulSoup or Scrapy assist in collecting data from various websites.
• APIs: Access data through Application Programming Interfaces (APIs) offered by various
platforms such as social media APIs (Twitter/X, Reddit), news aggregators, or linguistic
databases.
• PDFs: Extract text from PDF documents relevant to the project using libraries
like PyPDF2 or PDFMiner.
(iii) Nobody has the Data
• Engaging Trusted Clients: Collaborate with trustworthy clients or users willing to share
anonymized data relevant to the project’s goals.
• Data Generation: If viable, companies can generate synthetic data or collect information
through surveys, interviews, or user-generated content to build a dataset from scratch.
2. Text Preprocessing:
Text preprocessing is a critical phase in NLP, encompassing various steps to refine raw text data for meaningful
analysis and model training.
(i) Basic Cleaning:
Eliminating irrelevant or disruptive elements from the text:
• HTML Tag Removal: Stripping out HTML tags is crucial when working with web-based text
sources. These tags contain formatting information and are unnecessary for linguistic analysis.
• Handling Emojis: Managing emojis involves converting them to textual representations
using emoji library or removing them entirely, depending on their relevance to the analysis.
• Basic Spell Checks: Performing rudimentary spell checks to rectify common typographical
errors and ensure consistency in the text.
(ii) Basic Preprocessing
Prepare the text for further analysis by applying fundamental transformations:
• Tokenization: Segmenting text into smaller units such as words or sentences (word
tokenization and sentence tokenization). This step breaks down the text into manageable
chunks.
• Stop Word Removal: Eliminating common and less meaningful words (stop words) like “the,”
“is,” etc., which don’t contribute significantly to the meaning of the text.
• Stemming/Lemmatization: Reducing words to their root forms — stemming removes
prefixes/suffixes, while lemmatization maps words to their base or dictionary form, aiding in
standardization.
• Lowercasing: Converting all text to lowercase to ensure uniformity in text analysis, as case
sensitivity can affect certain NLP tasks.
• Language Detection: Identifying the language of the text, is especPally useful when dealing
with multilingual content.
U20CSST01 - NATURAL LANGUAGE PROCESSING
3. Feature Engineering :
• Transforming raw text data into numerical features that machine learning models can comprehend and
utilize effectively.
• The goal is to represent text in a format that captures semantic meaning, contextual information, and
relationships between words.
It can be done through various techniques:
(i) Bag of Words (BoW)
• Represents text as a collection of unique words disregarding grammar or word order.
• Creates a matrix where rows represent documents and columns represent unique words, with
values indicating word occurrence frequencies.
• Simple yet effective, but loses sequence information and context.
(ii) Term Frequency-Inverse Document Frequency (TF-IDF)
• Measures the importance of words in a document relative to a corpus.
• Considers both the frequency of a term in a document and its rarity across the corpus.
• Assigns higher weights to rare terms that are more discriminative.
(iii) Word Embeddings (Word2Vec, GloVe, FastText)
• Techniques that map words or phrases to dense vector representations in a continuous vector
space.
• Capture semantic relationships between words by placing similar words closer in the vector
space.
• Retain semantic meaning and context, useful for capturing word analogies and semantic
similarities.
(iv) N-Gram Models
• Captures sequences of adjacent words (bigrams, trigrams, etc.) as features.
• Preserves some sequence information, aiding in capturing context in language.
(v) Dependency Parsing
• Represents the grammatical structure of sentences as features.
• Captures relationships between words through syntactic dependencies.
4. Modelling :
The heart of the pipeline - models are applied and evaluated using different approaches:
DL models use neural networks with multiple layers to learn complex patterns and representations from raw
data.
Applications:
• Recurrent Neural Networks (RNNs): Effective for sequence-based tasks like language
modelling, sentiment analysis, or machine translation.
• Transformers: Particularly potent for attention-based mechanisms, excelling in tasks like
language translation, text generation, and summarization due to their ability to capture long-
range dependencies efficiently.
(iv) Cloud APIs
Cloud-based APIs offer pre-built, scalable models accessible via APIs, saving time and resources.
Applications:
• Google Cloud Natural Language API: Offers sentiment analysis, entity recognition, and
language detection.
• Microsoft Azure Text Analytics API: Provides sentiment analysis, key phrase extraction, and
named entity recognition.
5. Evaluation:
Encompassing intrinsic and extrinsic assessments to comprehensively gauge model performance from both
technical and practical standpoints.
(i) Intrinsic Evaluation
Intrinsic evaluation focuses on assessing the technical aspects and capabilities of the model in isolation, without
considering its real-world application.
Examples of Intrinsic Metrics:
• Accuracy: Measures the ratio of correctly predicted instances to the total instances in the
dataset.
• Precision, Recall, F1-score: Assess the model’s performance in binary or multi-class
classification tasks.
• Perplexity: Evaluates the language model’s predictive capability in language generation tasks.
• BLEU Score: Measures the quality of machine-translated text against a reference translation.
(ii) Extrinsic Evaluation
Extrinsic evaluation measures the model’s performance in real-world applications or business contexts,
considering its impact and utility in practical scenarios.
Examples of Extrinsic Evaluation Metrics:
• Business Metrics: Metrics aligned with specific business goals or outcomes, such as customer
satisfaction scores, revenue impact, or user engagement rates.
• Task-Specific Metrics: Metrics directly relevant to the NLP task at hand, like sentiment
analysis accuracy for customer feedback or document classification precision for information
retrieval systems.
• User-Centric Evaluation: Soliciting user feedback, surveys, or usability testing to assess user
satisfaction and experience with the NLP application.
6. Deployment :
NLP pipeline marks the transition of the developed model from the development environment to a production
environment, followed by continuous monitoring and adaptation to ensure sustained performance and relevance.
(i) Deployment
• Rolling out the Model: Moving the trained NLP model from the development environment to
a production environment where it can be utilized in real-world applications.
• Infrastructure Setup: Configuring the necessary infrastructure, integrating the model into the
existing systems, and ensuring scalability and reliability.
• Testing and Validation: Thoroughly testing the deployed model to ensure it functions as
expected and delivers accurate results in the production environment.
(ii) Monitoring
• Continuous Performance Oversight: Constantly monitoring the model’s performance,
including its accuracy, efficiency, and response time in real-time or at regular intervals.
U20CSST01 - NATURAL LANGUAGE PROCESSING
• Alert Systems: Implementing alert systems or triggers to notify about deviations or anomalies
in the model’s behaviour, ensuring timely interventions.
(iii) Update
• Adaptation to Dynamic Data: Adapting the model to changing data patterns or evolving
requirements by periodically updating and retraining the model.
• Improvement Iterations: Incorporating feedback, identifying areas for improvement, and
fine-tuning the model to enhance its performance or address changing user needs.
• Version Control: Maintaining version control to track model iterations and changes, ensuring
transparency and reproducibility.
Word Structure :
i) Tokens :
• Words in English are delimited only by whitespace and punctuation (the marks, such as full stop,
comma, and brackets)
• Example: Will you read the newspaper? Will you read it? I won’t read it.
twowords here: words newspaper and won’t.
newspaper- derivational structure- distinguished from the isolated news and paper.
The structure of won’t could be parsed as – will not .
ii) Lexemes :
• One linguistic form- in the given context, but also the concept behind the form and the set of alternative
forms that can express it.
• Set of alternative forms- lexemes or lexical items.
• Divided by their behaviour into the lexical categories- verbs, nouns, adjectives, conjunctions or other
parts of speech.
• Citation form of a lexeme - lemma.
• Example: Did you see him? I didn’t see him. I didn’t see anyone.
tokenization of didn’t and investigation of the internal structure of anyone.
iii) Morphemes:
• Associate the properties of word forms with their structural components. These components are usually
called segments or morphs.
• The morphs that by themselves represent some aspect of the meaning of a word are called morphemes
of some function.
MORPHOLOGY :
• Morphology is the study of morphemes – the smallest units of meaning in a language.
• Morphemes can be either free (stand-alone words) or bound (prefixes, suffixes, and infixes).
• The combination of morphemes forms complex words, conveying nuances of tense, plurality, and other
grammatical properties.
Types of Morphology:
i) Inflectional Morphology :
• Inflected forms are constructed from base forms and inflectional affixes.
• Inflection relates different forms of the same word.
• Morphological analysis involves breaking down words into their constituent morphemes (the smallest
units of meaning) and understanding their structure and formation.
• Various techniques can be employed to perform morphological analysis, each with its own strengths
and applications.
1. Stemming
Stemming reduces words to their base or root form, usually by removing suffixes. The resulting stems are
not necessarily valid words but are useful for text normalization.
Common ways to implement stemming in python:
U20CSST01 - NATURAL LANGUAGE PROCESSING
• Porter Stemmer: One of the most popular stemming algorithms, known for its simplicity and
efficiency.
• Snowball Stemmer: An improvement over the Porter Stemmer, supporting multiple languages.
• Lancaster Stemmer: A more aggressive stemming algorithm, often resulting in shorter stems.
2. Lemmatization
Lemmatization reduces words to their base or dictionary form (lemma). It considers the context and part of
speech, producing valid words. To implement lemmatization in python, WordNet Lemmatizer is used,
which leverages the WordNet lexical database to find the base form of words.
3. Morphological Parsing
Morphological parsing involves analyzing the structure of words to identify their morphemes (roots,
prefixes, suffixes). It requires knowledge of morphological rules and patterns. Finite-State Transducers
(FSTs) is uses as a tool for morphological parsing.
Finite-State Transducers (FSTs)
FSTs are computational models used to represent and analyze the morphological structure of words. They
consist of states and transitions, capturing the rules of word formation.
Applications:
• Morphological Analysis: Parsing words into their morphemes.
• Morphological Generation: Generating word forms from morphemes.
5. Rule-Based Methods
Rule-based methods rely on manually defined linguistic rules for morphological analysis. These rules can
handle specific language patterns and exceptions.
Applications:
• Affix Stripping: Removing known prefixes and suffixes to find the root form.
• Inflectional Analysis: Identifying grammatical variations like tense, number, and case.
CHALLENGES IN NLP:
DOCUMENT STRUCTURE:
• Document Structuring is a subtask of Natural language generation, which involves deciding the order
and grouping (for example intoparagraphs) of sentences in a generated text .
• It is closely related to the Content determination NLG task.
1. Sentence Boundary Detection
2. Topic Boundary Detection
• In information retrieval, if long documents can be segmented into shorter, topically coherent segments,
then only the segment that is about the user's query could be retrieved.
• For multiparty meetings, the task of topic segmentation is inspired by discourse analysis.
• For official and well-structured meetings, the topics are segmented according to the agenda items,
whereas for more casual conversational-style meetings, the boundaries are less clear.
• For conversational speech, the topic boundaries may not be absolute. Hence they are more complex.
• In text, topic boundaries are usually marked with distinct segmentation cues, such as headlines and
paragraph breaks. These cues are absent in speech. However, speech provides other cues, such as pause
duration and speaker changes.
• Topic segmentation is a nontrivial problem without a very high human agreement because of many
natural-language-related issues and hence requires a good definition of topic categories and their
granularities
• For sentence or topic segmentation, the problem is defined as finding the most probable sentence or
topic boundaries.
• The natural unit of sentence segmentation is words and of topic segmentation is sentence, as we can
assume that topics typically do not change in the middle of a sentences.
• The words or sentences are then grouped into categories belonging to one sentences or topic as
boundaries and non-boundaries.
• The classification can be done at each potential boundary i (local modelling); then, the aim is to
estimate the most probable boundary type ŷ¡ for each candidate X₁
• These models are trained on large amounts of unlabeled data and can be fine-tuned to perform various
NLP tasks.
• They work by learning the probability distribution of words in a language and use this knowledge to
generate new text that matches the input's context.
• Generative modelling defines how a dataset is generated.
U20CSST01 - NATURAL LANGUAGE PROCESSING
• It tries to understand the distribution of data points, providing a model of how the data is actually
generated in terms of a probabilistic model.
Complexity of Approaches
• Discriminative approach
In terms of complexity, training of discriminative approaches is more complex than training of
generative ones.
Since, they require multiple passes over the training data to adjust for their feature weights.
• Generative models
Generative models such as HELMs can handle multiple orders of magnitude larger training sets.
But, they do not cope well with unseen events.
• Discriminative classifiers
They allow for a wider variety of features and perform better on smaller training sets.
Predicting with discriminative classifiers is also slower, even though the models are relatively simple
(linear or log-linear).
• Sequence approaches
Compared to local approaches, sequence approaches bring the additional complexity of decoding:
To find the best sequence of decisions requires evaluating all possible sequences of decisions.