Skip to content
SDB
Natural Language Processing

Chapter 05 · intermediate · 28 min

Semantic Analysis

Word meaning, semantic similarity, word sense disambiguation, and semantic role labeling

Subhendu Datta BhowmikAI Tutorials

What Is Semantic Analysis?

Semantic analysis goes beyond syntax to determine the meaning of words, phrases, and sentences. While syntax answers "is this grammatical?", semantics answers "what does it mean?".

Levels of Meaning

LevelQuestionExample
Lexical semanticsWhat does this word mean?"bank" = financial vs. river
Compositional semanticsHow do words combine to mean?"not good" ≠ "good"
Sentence semanticsWhat does this sentence mean?"The chicken is ready to eat"
Discourse semanticsHow do sentences relate?"He saw the bank. He deposited money."

Lexical Semantic Relations

RelationDefinitionExample
SynonymySame meaning"big" ↔ "large"
AntonymyOpposite meaning"hot" ↔ "cold"
PolysemyOne word, multiple related senses"run" (jog / operate / flow)
HomonymySame form, unrelated meanings"bat" (animal / sports)
HypernymyIs-a (general)"animal" is hypernym of "dog"
HyponymyIs-a (specific)"poodle" is hyponym of "dog"
MeronymyHas-part"wheel" is meronym of "car"

Compositionality

The Principle of Compositionality (Frege's principle): the meaning of a complex expression is determined by the meanings of its parts and how they are combined.

Violations:

  • Idioms: "kick the bucket" ≠ kick + bucket
  • Metaphors: "time flies" — time doesn't literally fly
  • Negation scope: "I didn't say he stole the money" has 7 different meanings depending on stress

Word Sense Disambiguation (WSD)

Approaches to WSD

1. Knowledge-based (Lesk Algorithm)

The Lesk algorithm selects the sense whose WordNet definition has the highest overlap with surrounding words:

sense=argmaxssenses(w)context(w)gloss(s)\text{sense}^* = \arg\max_{s \in \text{senses}(w)} |\text{context}(w) \cap \text{gloss}(s)|

Simple but surprisingly effective. Extended Lesk also considers related synsets (hypernyms, hyponyms).

2. Supervised ML

Train a classifier for each target word using:

  • Surrounding words (bag-of-words window)
  • POS tags of neighbors
  • Syntactic dependencies

Requires sense-annotated training data (SemCor, WordNet corpus).

3. Transformer-based WSD

BERT naturally performs WSD implicitly: contextual embeddings of polysemous words are different in different contexts:

  • "I went to the bank" → BERT embedding near "financial institution" cluster
  • "Fishing by the river bank" → BERT embedding near "riverbank" cluster

EWISER, ESC, and BEM are state-of-the-art WSD systems using BERT + WordNet.

Semantic Similarity

Semantic similarity measures how similar two pieces of text are in meaning (not just lexically):

ApproachFormula / MethodStrength
WordNet path similarity\text{sim} = \frac{1}{\text{path_len}(c_1, c_2) + 1}Interpretable
Wu-PalmerBased on LCS depthHandles hierarchy
Jaccard (BoW)$\frac{A \cap B
Cosine (TF-IDF)uvuv\frac{\mathbf{u} \cdot \mathbf{v}}{\|\mathbf{u}\|\|\mathbf{v}\|}Scalable
Sentence embeddingsCosine of SBERT vectorsState-of-the-art

Semantic Role Labeling (SRL)

SRL (also called "shallow semantic parsing") identifies the predicate-argument structure of a sentence — answering who did what to whom, where, when, and how.

PropBank Roles

PropBank defines argument roles relative to a predicate:

RoleMeaningExample ("Alice gave Bob a book")
ARG0Agent / giverAlice
ARG1Theme / givena book
ARG2Recipient / beneficiaryBob
ARGM-LOCLocationin the library
ARGM-TMPTimeyesterday
ARGM-MNRMannercarefully
ARGM-NEGNegationnot

FrameNet

FrameNet uses semantic frames — abstract situation types with participant roles (frame elements):

  • Frame: COMMERCE_BUY
  • Frame elements: Buyer, Goods, Seller, Money

"Alice bought a laptop from Apple for $1000"

  • Buyer = Alice, Goods = laptop, Seller = Apple, Money = $1000

Why SRL Matters

SRL is the bridge between raw text and knowledge:

  • Information extraction: extract structured facts from unstructured text
  • Question answering: "Who gave what to whom?"
  • Machine translation: preserving semantic roles across languages
  • Summarization: identifying which information is most salient
WSD, Semantic Similarity, and SRLpython
import nltk
from nltk.corpus import wordnet as wn
from nltk.wsd import lesk
import spacy

nltk.download(['wordnet', 'punkt', 'stopwords', 'brown', 'semcor'], quiet=True)

# ─── 1. Word Sense Disambiguation (Lesk) ─────────────────────
contexts = [
    ("I went to the bank to deposit my paycheck", "bank"),
    ("The river bank was covered with wildflowers", "bank"),
    ("The plane was flying over the bank of clouds", "bank"),
]
print("Word Sense Disambiguation (Lesk):")
for context, word in contexts:
    tokens = context.split()
    sense = lesk(tokens, word, 'n')
    if sense:
        print(f"  '{context}'")
        print(f"  → Sense: {sense.name()}: {sense.definition()[:70]}
")

# ─── 2. Semantic Similarity with WordNet ─────────────────────
pairs = [
    ("dog", "wolf"),
    ("dog", "cat"),
    ("dog", "table"),
    ("car", "automobile"),
    ("happy", "joyful"),
]
print("WordNet Semantic Similarity:")
print(f"{'Pair':<25} {'Path Sim':>10} {'Wu-Palmer':>12}")
for w1, w2 in pairs:
    s1 = wn.synsets(w1, pos='n')
    s2 = wn.synsets(w2, pos='n')
    if s1 and s2:
        path = s1[0].path_similarity(s2[0]) or 0
        wup = s1[0].wup_similarity(s2[0]) or 0
        print(f"  {w1}-{w2:<20} {path:>10.3f} {wup:>12.3f}")

# ─── 3. Sentence Similarity with Sentence Transformers ───────
# pip install sentence-transformers
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np

model = SentenceTransformer('all-MiniLM-L6-v2')

sentences = [
    "The cat sat on the mat.",
    "A feline rested on the rug.",
    "The stock market crashed yesterday.",
    "I love pizza with extra cheese.",
]
embeddings = model.encode(sentences)
sim_matrix = cosine_similarity(embeddings)

print("\nSentence Similarity Matrix:")
for i, s1 in enumerate(sentences):
    for j, s2 in enumerate(sentences):
        if i < j:
            print(f"  {sim_matrix[i,j]:.3f} | '{s1[:40]}' ↔ '{s2[:40]}'")

# ─── 4. Semantic Role Labeling with AllenNLP ─────────────────
# pip install allennlp allennlp-models
from allennlp.predictors.predictor import Predictor

predictor = Predictor.from_path(
    "https://storage.googleapis.com/allennlp-public-models/structured-prediction-srl-bert.2020.12.15.tar.gz"
)

srl_sentence = "Alice carefully gave Bob an interesting book about linguistics."
result = predictor.predict(sentence=srl_sentence)
print(f"\nSRL for: '{srl_sentence}'")
for verb_info in result["verbs"]:
    print(f"  Verb: {verb_info['verb']}")
    print(f"  Tags: {list(zip(result['words'], verb_info['tags']))}")

# ─── 5. Simple SRL with spaCy patterns ───────────────────────
nlp = spacy.load("en_core_web_sm")
doc = nlp("Alice bought a laptop from Apple for one thousand dollars.")
print(f"\nSimple semantic roles from dependency parse:")
for token in doc:
    if token.dep_ == "ROOT":
        print(f"  Predicate (verb): {token.text}")
    elif token.dep_ == "nsubj":
        print(f"  ARG0 (agent/subject): {token.text}")
    elif token.dep_ in ("obj", "dobj"):
        print(f"  ARG1 (theme/object): {token.text}")
    elif token.dep_ == "prep" and token.text == "from":
        print(f"  ARG2 (source): {list(token.children)}")
    elif token.dep_ == "prep" and token.text == "for":
        print(f"  ARGM-MNY (money): {list(token.children)}")

Knowledge check

In the sentence "The chicken is ready to eat", what semantic ambiguity exists and which linguistic level does it belong to?

Summary

  • Lexical semantics covers synonymy, antonymy, polysemy, homonymy, hypernymy, and meronymy
  • WSD resolves polysemy using context; Lesk uses WordNet gloss overlap; BERT-based methods are state-of-the-art
  • Semantic similarity ranges from WordNet path similarity (interpretable) to sentence embeddings (SBERT, accurate)
  • SRL identifies predicate-argument structure: ARG0 (agent), ARG1 (theme), ARG2 (recipient), ARGM modifiers
  • FrameNet provides richer semantic frames (COMMERCE_BUY, MOTION) with named frame elements

Next: Discourse & Pragmatics — understanding how context shapes meaning across sentences.

Natural Language Processing