Sentiment analysis
Sentiment analysis (opinion mining): methods to detect polarity and subjectivity in text using lexicons, features (TF‑IDF, embeddings) and classifiers, with evaluation and common pitfalls.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Sentiment analysis is used by engineers to automatically detect whether text (reviews, tweets, comments) expresses positive, negative or neutral opinions. It helps in product feedback, social-media monitoring, customer support routing and business intelligence.
Key ideas
Subjectivity: whether text expresses an opinion (subjective) or factual information (objective).
Opinion mining: often used as a synonym of sentiment analysis; emphasises extracting targets (entities or aspects) and the opinion holder.
Problem formulation (classification): sentiment analysis is usually formulated as a supervised classification problem. Formally: given an instance x in feature space X, learn a function f: X -> Y, where Y is a finite set of labels (e.g., {+1, -1, 0}). Assumption: training and test data are drawn from the same distribution (IID). If this assumption fails, domain adaptation methods are needed. For binary logistic regression, encode y in {0,1} (not {-1,+1}); SVMs often use labels {-1,+1}.
Levels: document-level (label whole document), sentence-level, and aspect-based (also called fine-grained) where we find sentiment about a specific aspect of an entity.
Two main approaches:
- Lexicon-based: use a dictionary that maps words/phrases to sentiment scores (positive/negative, or numeric). Score a text by summing or averaging token scores. Assumption: word sentiments combine (usually additively); this fails for negation and sarcasm unless handled explicitly.
- Supervised learning: extract features from labeled examples and train a classifier (e.g., logistic regression, SVM, neural networks). Assumption: labelled training data exists and matches test domain.
Features:
- Bag-of-words (BoW): counts or binary presence of tokens.
- TF‑IDF: term-frequency adjusted by inverse document frequency; reduces weight of common words.
- n-grams: uni/bi/tri-grams capture local context (e.g., "not good").
- Word embeddings: dense vector representations (word2vec, GloVe) that capture semantic similarity.
- Syntactic features, part-of-speech tags, emoticons, punctuation, capitals, and lexicon counts.
Preprocessing: tokenisation, lowercasing (when important), stopword removal (optional), stemming/lemmatisation (can help or hurt), handling emoticons and emojis, normalising elongated words, and handling negation (see below).
Negation handling: detect negation words (not, never) and flip or mark following tokens until punctuation; common trick: append "_NEG" to tokens in negation scope so 'good' -> 'good_NEG'.
Evaluation: use accuracy, precision, recall, F1. For class-imbalanced data prefer F1 or per-class metrics. Use confusion matrix to inspect errors. State whether you report macro, micro, or weighted averages; for multi-class datasets, prefer macro-F1.
Advanced topics: aspect-based sentiment (find sentiment toward specific attributes), sarcasm detection (very hard), domain adaptation (models trained on one domain often fail on another), multilingual sentiment (requires resources like IndoWordNet or translated lexicons), transformer-based contextual models (BERT) fine-tuned for sentiment give state-of-the-art results but need compute and labelled data.
Assumptions to state in exam answers: that training and test distributions are comparable; lexicon-based additivity of scores; that tokens and contexts are correctly identified by tokenisation.
Diagram to draw (for pipeline question): draw boxes left-to-right labelled: Raw text -> Preprocessing (tokenisation, lowercasing) -> Feature extraction (TF‑IDF / embeddings / lexicon counts) -> Classifier (logistic regression / SVM / BERT) -> Output label. Label arrows and show an optional feedback loop for error analysis.
Formulas
tf(t,d) = count of term t in document d where tf is unitless; applies when using raw term frequency.
idf(t, D) = log( N / (df_t) ) where N is total number of documents in corpus D (unitless), df_t is number of documents containing term t, applies for the basic IDF; smoothing variants add 1 to numerator/denominator.
tfidf(t,d,D) = tf(t,d) * idf(t,D) unitless; applies when building TF‑IDF features.
sigmoid(z) = 1 / (1 + exp(-z)) unitless; z is real-valued score (e.g., w·x + b); applies in logistic regression for binary probability.
p(y=1 | x; w,b) = sigmoid(w·x + b) unitless; probability that label is 1 given features x and parameters w,b.
Cross-entropy loss L = - [ y log p + (1-y) log(1-p) ] unitless; for a single binary example, y in {0,1}, p = p(y=1|x).
Gradient w.r.t w: ∂L/∂w = (p - y) x unitless; used in logistic regression training by gradient descent.
Accuracy = (TP + TN) / (TP + TN + FP + FN) unitless; proportion of correct predictions.
Precision = TP / (TP + FP) unitless; Recall = TP / (TP + FN) unitless.
F1 = 2 * (Precision * Recall) / (Precision + Recall) unitless; harmonic mean of precision and recall. For multi-class classification with K classes, use softmax p(y=k|x) = exp(z_k) / sum_j exp(z_j) and cross-entropy L = - sum_k y_k log p_k.
Notes: TP = true positives, FP = false positives, TN = true negatives, FN = false negatives.
Worked examples
Example 1 — Lexicon-based rule (Python). This is a small running program to illustrate negation handling.
# lexicon_rule_based.py
lexicon = {
'good': 1,
'great': 2,
'excellent': 2,
'bad': -1,
'terrible': -2,
'boring': -1,
'love': 2,
'hate': -2
}
negations = set(['not', "don't", 'never', 'no'])
def sentiment_score(text):
tokens = text.lower().split()
score = 0
i = 0
while i < len(tokens):
tok = tokens[i].strip('.,!?')
if tok in negations and i+1 < len(tokens):
next_tok = tokens[i+1].strip('.,!?')
val = lexicon.get(next_tok, 0)
score -= val # invert the next token's contribution
i += 2
else:
score += lexicon.get(tok, 0)
i += 1
return score
if __name__ == '__main__':
s = 'The movie was not good but the acting was great.'
sc = sentiment_score(s)
label = 'positive' if sc > 0 else 'negative' if sc < 0 else 'neutral'
print('Input:', s)
print('Score:', sc, '->', label)
Sample run and exact output:
Input: The movie was not good but the acting was great. Score: 1 -> positive
Explanation: 'not good' contributes -1 (inversion), 'great' contributes +2, total +1 => positive.
Example 2 — Supervised TF‑IDF + Logistic Regression (Python, sklearn).
# sentiment_sklearn.py
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
train_texts = [
'I loved the movie, it was fantastic and touching',
'One of the worst films I have seen, terrible plot',
'The plot was good but acting was bad',
'An excellent film with great acting',
'I did not like the film, it was boring and long',
'It was an okay movie, not great'
]
train_labels = [1, 0, 0, 1, 0, 0]
test_texts = [
'I really loved the acting and the story',
'The film was long and boring, I hated it'
]
vec = TfidfVectorizer(ngram_range=(1,2))
X = vec.fit_transform(train_texts)
model = LogisticRegression(random_state=0, solver='liblinear', max_iter=1000)
model.fit(X, train_labels)
X_test = vec.transform(test_texts)
preds = model.predict(X_test)
map_label = {1: 'positive', 0: 'negative'}
print('Predictions:')
for t, p in zip(test_texts, preds):
print(t)
print('->', map_label[p])
print('\nExact accuracy on these two test samples:', (preds == [1,0]).mean())
Exact output when run:
Predictions: I really loved the acting and the story -> positive The film was long and boring, I hated it -> negative
Exact accuracy on these two test samples: 1.0
Notes: randomness is fixed by random_state=0. With such a small dataset a perfect accuracy on two examples can occur; in exams note that real evaluation uses held-out sets and cross-validation.
Example 3 — Derivation (short) of logistic regression gradient used in exam answers: Start with p = sigmoid(z) where z = w·x + b. Cross-entropy for one example: L = -[ y log p + (1-y) log(1-p) ]. Differentiate w.r.t w:
- dp/dz = p(1-p).
- dL/dz = -[ y (1/p) dp/dz - (1-y) (1/(1-p)) dp/dz ] = -( (y - p) / (p(1-p)) ) dp/dz = p - y.
- dL/dw = (dL/dz) (dz/dw) = (p - y) x. This is the gradient used in batch or SGD updates.
Common mistakes
- Overfitting small labelled data: complex models without regularisation.
- Using accuracy on imbalanced data; prefer F1 or per-class recall.
- Not handling emoticons/emoji which carry strong sentiment in social media.
- Treating sarcasm as normal sentiment: sarcasm often flips polarity but needs special handling.
- Not stating assumptions: exam answers should state IID assumption for supervised learning and additivity for lexicon methods.
For your exam
Types of questions:
- Definitions: define sentiment analysis, polarity, subjectivity, aspect-based sentiment.
- Short notes: pipeline, lexicon-based vs supervised approaches, handling negation.
- Derivations: derive TF‑IDF formula variants, derive logistic regression cross-entropy and gradient (show steps above).
- Numericals/programs: implement simple rule-based sentiment or show TF‑IDF calculation for small corpus.
- Diagrams: draw the pipeline boxes and label preprocessing and feature steps.
What a full-marks answer includes:
- Clear definitions with bolded term (in exam write 'Definition: ...').
- Assumptions stated (IID, additivity, etc.).
- For derivations: every algebra step and explanation (like chain rule use). For program questions: correct code plus sample input/output and explanation of decisions (e.g., choice of vectoriser, negation handling).
Quick check
- What is the difference between polarity and subjectivity?
- Give the TF‑IDF formula and explain the purpose of IDF.
- State the gradient of the binary cross-entropy loss w.r.t. weights in logistic regression.
Answers: 1) Polarity is positive/negative/neutral; subjectivity is whether text expresses opinion versus factual content. 2) TF‑IDF = tf * idf where idf = log(N/df) (IDF downweights common terms across documents). 3) ∂L/∂w = (p - y) x where p = sigmoid(w·x + b).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?