Sentiment Analysis, Clustering, and Topic Modeling Notes

Sentiment Analysis

  • Sentiment analysis is an NLP technique used to determine the emotional tone of a text.
  • It classifies text as positive, negative, or neutral by analyzing words and phrases.
  • Applications:
    • Social media monitoring
    • Customer feedback analysis
    • Brand reputation management
    • Product reviews analysis

VADER Sentiment Analysis

  • VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon-based sentiment analysis tool optimized for social media and short texts.
  • Why Use VADER?
    • Rule-based: Assigns predefined scores to words based on their sentiment.
    • Handles negations & intensifiers: Words like "not good" or "very happy" are considered.
    • Works well on short texts (e.g., tweets, comments, reviews).
  • How VADER Works:
    • Positive words (e.g., "amazing", "excellent") → +1 to +4
    • Negative words (e.g., "terrible", "worst") → -1 to -4
    • Neutral words (e.g., "the", "is", "and") → 0
    • Final score: Compound score between -1 (negative) to +1 (positive)
Compound Score Computation

The compound score is calculated using the sum of valence scores of each word in the text, adjusted for:

  • Punctuation emphasis (e.g., "great!!!" has a stronger score than "great").
  • Capitalization emphasis (e.g., "GREAT" is stronger than "great").
  • Modifiers like 'very' or 'slightly' that affect intensity.
  • Negations (e.g., "not happy" reduces the score of "happy").
Step-by-Step Calculation Example: "This product is absolutely amazing and I love it!"
  • Step 1: Assign Base Scores from Lexicon
    • "amazing" → 0.585 (positive sentiment)
    • "love" → 0.669 (positive sentiment)
    • "absolutely" → (intensifier, boosts "amazing")
  • Step 2: Apply Intensifier Modifier
    • VADER applies a standard intensification factor of ~0.293.
    • Adjusted score for "amazing": boostedscore=0.585×(1+0.293)=0.585×1.293=0.756boosted _score = 0.585 \times (1+0.293) = 0.585\times1.293 = 0.756
  • Step 3: Sum the Adjusted Scores
    • 0. 756(boosted "amazing") + 0.669("love") = 1.425
    • Rounding to two decimal places: sum(s)≈1.43sum(s) \approx 1.43
How to Compute the Normalized Score:
  • Apply the VADER normalization formula.

  • Compute the Denominator.

  • Compute the final compound score.

  • Round to Two Decimal Places.

    • VADER rounds the result to two decimal places: 0.35
    • The sentiment is positive because 0.35 > 0.05
VADER Sentiment Score Components

Clustering

  • Clustering is an unsupervised machine learning technique used to group similar data points based on their features.
  • It is applied in text mining, customer segmentation, image processing, and anomaly detection.
  • The primary goal is to discover hidden patterns without predefined labels.

Types of Clustering Algorithms

1. Partitioning Clustering (e.g., K-Means)
  • Divides data into K groups, where each data point belongs to the closest cluster centroid.
  • Example algorithms: K-Means, K-Medoids.
  • Best for: Large datasets with well-defined clusters.
2. Hierarchical Clustering
  • Creates a tree-like structure (dendrogram) showing how clusters merge or split.
  • Divided into:
    • Agglomerative (Bottom-Up): Each data point starts as its own cluster and merges iteratively.
    • Divisive (Top-Down): The entire dataset is treated as one cluster and is split recursively.
  • Best for: Small datasets, visualization of relationships.
3. Density-Based Clustering (e.g., DBSCAN)
  • Groups points that are closely packed together and marks outliers as noise.
  • Best for: Irregularly shaped clusters, noise handling.
4. Model-Based Clustering (e.g., Gaussian Mixture Model - GMM)
  • Assumes data is generated by a mixture of probability distributions (e.g., Gaussian distributions).
  • Best for: Soft clustering, probabilistic assignments.

How K-Means Clustering Works

  • K-Means is a centroid-based clustering algorithm that aims to minimize the sum of squared distances between data points and their cluster centroids.
Steps in K-Means Algorithm
  1. Choose the number of clusters (K).
  2. Initialize K cluster centroids randomly.
  3. Assign each data point to the nearest centroid.
  4. Compute the new centroids by averaging the points in each cluster.
  5. Repeat steps 3-4 until centroids no longer change (convergence).

Mathematically, the objective function to minimize is:

J=∑<em>i=1K∑</em>x∈S<em>i∣∣x−μ</em>i∣∣2{J = \sum<em>{i=1}^{K} \sum</em>{x \in S<em>i} ||x - \mu</em>i||^2}

Evaluating Clustering Performance

  • Since clustering is unsupervised, evaluating its performance requires different metrics:
1. Within-Cluster Sum of Squares (WCSS)
  • Measures how compact clusters are.
  • Lower WCSS indicates better clustering.
2. Silhouette Score
  • Measures how well each data point is assigned to its cluster.
  • Ranges from -1 to 1:
    • Near 1: Well-clustered.
    • Near 0: Overlapping clusters.
    • Negative: Incorrect clustering.
3. Davies-Bouldin Index
  • Measures the average similarity ratio between clusters.
  • Lower values indicate better clustering.
4. Dunn Index
  • Measures the ratio between the minimum inter-cluster distance and the maximum intra-cluster distance.
  • Higher values are better.

Choosing the Optimal Number of Clusters

  • K-Means requires specifying K in advance. Two common methods to find the best K are:
1. Elbow Method (Using WCSS)
  • Plot WCSS for different values of K.
  • Identify the "elbow point" where WCSS stops decreasing sharply.
  • The corresponding K is optimal.
2. Silhouette Score Analysis
  • Compute Silhouette Scores for different values of K.
  • Choose the K with the highest Silhouette Score.

Why Use TF-IDF with Clustering?

  • TF-IDF (Term Frequency-Inverse Document Frequency) helps in:
    • Removing stopwords (common words like "the", "is")
    • Assigning more weight to meaningful words
    • Improving distance-based clustering performance
  • After applying TF-IDF, documents are represented as vectors in a high-dimensional space. Clustering then groups similar documents based on cosine similarity or Euclidean distance.

K-Means vs. Other Clustering Methods for Text Data

Word2Vec for Clustering
  • Word2Vec transforms words into continuous vector representations, capturing semantic meanings. Similar words are located close together in the vector space.
  • Two main models:
    • CBOW (Continuous Bag of Words): Predicts the current word based on the surrounding context.
    • Skip-Gram: Predicts the surrounding words based on the current word.
  • These models generate high-dimensional vectors that encode relationships such as:
    • "king" - "man" + "woman" ≈ "queen"

Why Use Word2Vec for Clustering?

  • Traditional approaches (e.g., TF-IDF + KMeans) treat words as independent tokens, losing deeper contextual and semantic relationships.
  • By using Word2Vec, we:
    • Encode semantic similarity: e.g., "smart" and "intelligent" get similar vectors.
    • Improve cluster quality: Groups of documents with similar themes, even with different vocabulary, can be clustered more meaningfully.
    • Reduce dimensionality: Vector representations are dense and more compact than sparse BoW or TF-IDF.

How It Works in a Clustering Context

  1. Preprocessing:
    • Texts are cleaned (lowercased, punctuation removed, stopwords filtered).
    • Remaining meaningful words are tokenized.
  2. Vectorization:
    • Each list of words (document) is transformed into a single vector using Word2Vec.
    • This is done by averaging or summing the word vectors of all words in the document.
  3. Clustering:
    • These document-level vectors are input into KMeans (or another clustering algorithm).
    • KMeans groups documents into k clusters based on their vector similarities.
  4. Evaluation:
    • Clustering quality is measured using metrics like WCSS (Within-Cluster Sum of Squares) and Silhouette Score.
    • Visualization techniques like PCA help show how distinct or overlapping the clusters are.
Benefits
  • Captures semantic context of language.
  • Works well on short texts like tweets, feedback, or messages.
  • Boosts cluster interpretability and real-world relevance.
Challenges
  • Requires enough data to learn meaningful vectors.
  • Word2Vec may not capture polysemy (words with multiple meanings) unless further refined.
  • Short documents might lack sufficient word variety for strong vector signals.

Topic Modeling

  • Topic modeling is an unsupervised machine learning technique used to discover hidden thematic structures in large collections of text data.
  • It groups words into topics based on their co-occurrence across documents, helping to understand the main themes or subjects present in the corpus without labeled data.

Applications:

  • Text summarization
  • Document clustering and classification
  • Recommender systems
  • Sentiment and trend analysis
  • Organizing large text datasets (e.g., customer feedback, news articles, research papers)

Latent Dirichlet Allocation (LDA)

  • LDA is a popular probabilistic topic modeling method introduced by Blei, Ng, and Jordan (2003).
  • It assumes:
    1. Each document is a mixture of topics.
    2. Each topic is a distribution over words.
  • LDA works by estimating two hidden structures:
    • Topic distribution per document (θ\theta)
    • Word distribution per topic (ϕ\phi)
  • These distributions are learned through techniques like Expectation Maximization (EM) or Variational Bayes, based on a Bayesian framework using Dirichlet priors for both document-topic and topic-word distributions.
LDA Key Parameters:
  • k: number of topics (needs to be pre-defined)
  • docConcentration (α\alpha): prior for document-topic distribution
  • topicConcentration (β\beta): prior for topic-word distribution
  • maxIter: number of iterations for convergence
  • LDA is well-suited for interpretability, producing coherent word clusters (topics) that are easy to explain and visualize.

BERT-based Topic Modeling

  • Recent advances in NLP introduced contextual embeddings like BERT (Bidirectional Encoder Representations from Transformers).
  • These models represent words and documents in a high-dimensional vector space by capturing semantics and context.
How BERT-Based Topic Modeling Works:
  1. Convert documents to BERT embeddings (using sentence-transformers or similar models).
  2. Dimensionality reduction using algorithms like UMAP.
  3. Clustering (e.g., KMeans, HDBSCAN) on reduced vectors to group similar documents.
  4. Topic extraction from each cluster using word frequency, TF-IDF, or class-based TF-IDF (c-TF-IDF).
Advantages of BERT-based Models:
  • No need to predefine number of topics (if using HDBSCAN).
  • More semantically accurate (e.g., it can detect that "COVID-19" and "coronavirus" belong to the same theme).
  • Better handling of short texts and slang compared to LDA.

Evaluation Metrics

  • To assess the quality of topic models, we use various metrics. Two key ones for LDA are:
1. Log Likelihood
  • Measures how well the model predicts the observed data.
  • Higher is better.
  • It calculates the probability of the documents given the topic model: logP(D∣θ,ϕ)logP(D∣\theta,\phi)
  • Can be used to compare models with the same number of topics.
2. Perplexity
  • Measures how “surprised” the model is by the test data.
  • Derived from log likelihood.
  • Lower is better.
  • Perplexity=exp(−∑logP(w)N)Perplexity=exp(-\frac{\sum logP(w)}{N})
  • It is like inverse likelihood, penalizing poor word predictions.
  • Both log likelihood and perplexity are internal metrics—they do not directly tell you how “understandable” or “useful” topics are to humans.
3. Silhouette Score (mainly for BERT-based models)
  • Measures cluster quality.
  • Ranges from -1 to 1, where higher is better.
  • Evaluates how similar each document is to its own cluster vs. others.

Log Likelihood vs Perplexity

When choosing between Log Likelihood and Perplexity to evaluate topic models—especially LDA—it is helpful to understand what each metric tells you and how they differ in practical use:

Log Likelihood
  • Definition: The probability of the data (i.e., your documents) given the model's parameters.
  • Interpretation: A higher log likelihood means your model explains the data better.
  • Use: Helpful for comparing models during training or hyperparameter tuning (e.g., number of topics).
  • Scale: It can be a large negative number. You are comparing relative values (e.g., -25000 is better than 27000).
  • Use log likelihood when:
    • You are optimizing the model internally.
    • You want to compare models with the same dataset and vocabulary.
    • You are okay with values that are not human-interpretable but mathematically reliable.
Perplexity
  • Definition: Exponential of the negative average log likelihood per word.
  • Interpretation: A measure of how well the model predicts a sample; lower is better.
  • Use: Often used to assess model performance on unseen/test data.
  • Scale: More interpretable—think of it like a “loss” or “error” metric.
  • Use perplexity when:
    • You want a normalized, interpretable score across different models.
    • You are doing cross-validation or comparing train/test performance.
    • You are monitoring overfitting (perplexity on train ↓ and test ↑ = overfitting).
Which One to Choose?
SituationUse
Comparing models on the same corpusLog Likelihood
Comparing model performance across datasetsPerplexity
Evaluating generalization on test dataPerplexity
Debugging or optimizing during trainingLog Likelihood
Want a human-interpretable scorePerplexity
Prefer raw probability scoreLog Likelihood

Often, both are used together:

  • Log likelihood to monitor training
  • Perplexity to evaluate model generalization
  • But remember: these are internal metrics—they do not guarantee the topics are meaningful to humans.
  • So, you might also want to combine them with topic coherence or manual inspection if interpretability matters.

LDA vs BERT for Topic Modeling

CriteriaLDABERT-based
InterpretabilityHigh (clear word distributions)Moderate
Text TypeWorks best on long documentsGreat for short texts
Topic CoherenceDepends on preprocessing and priorsTypically higher due to contextual embeddings
Topic CountMust be specifiedCan be automatic (e.g., HDBSCAN)
SpeedFast, scalable in PySparkSlower, more computationally expensive
VisualizationSimple word cloudsRicher (e.g., embeddings map)
  • LDA is best when interpretability, simplicity, and scalability matter—especially in large datasets with well-formed text.
  • BERT-based methods are suitable when richer semantics are needed, especially for noisy, short, or informal texts.
  • Using Log Likelihood and Perplexity helps determine the best LDA configuration.
  • For modern NLP applications, combining traditional topic modeling with transformer embeddings gives the best of both worlds.

Ethical Considerations for Big Data Analysis

  • Big data analysis has transformed decision-making in healthcare, business, education, governance, and social sciences.
  • Organizations can uncover patterns, predict trends, and optimize processes by collecting, storing, and analyzing massive datasets.
  • However, the use of big data also raises significant ethical concerns, particularly about privacy, consent, bias, security, and accountability.
  • Addressing these concerns is essential to maintain public trust, avoid harm, and ensure fairness and transparency.

1. Privacy and Confidentiality

  • One of the most pressing ethical concerns in big data is the invasion of privacy.
  • As data is collected from various sources, such as social media, mobile devices, wearable technologies, and IoT systems, individuals may not be aware of the extent to which they are being monitored or how their data is used.
Ethical Principles Involved:
  • Respect for autonomy: Individuals have a right to control information about themselves.
  • Confidentiality: Personal data must be protected from unauthorized access.
Best Practices:
  • Use data anonymization and de-identification techniques.
  • Limit data collection to what is necessary for the stated purpose.
  • Establish clear data retention and deletion policies.

2. Informed Consent

  • Traditional models of informed consent are difficult to implement in big data contexts, especially when data is collected passively or reused for secondary analysis.
Ethical Principles Involved:
  • Informed consent: Individuals must voluntarily agree to data collection and understand how their data will be used.
Best Practices:
  • Develop user-friendly privacy policies and consent forms.
  • Use dynamic consent models where users can adjust their data-sharing preferences over time.
  • Inform users about the potential risks and benefits of data usage.

3. Data Bias and Fairness

  • Bias in data collection, algorithm design, or interpretation can lead to discriminatory outcomes, especially in predictive analytics used in policing, hiring, credit scoring, or healthcare.
Ethical Principles Involved:
  • Justice: Ensure fair treatment and equal opportunity.
  • Non-maleficence: Avoid causing harm through biased or inaccurate results.
Best Practices:
  • Audit datasets for representativeness and bias.
  • Use diverse teams to develop and validate algorithms.
  • Implement fairness-aware machine learning techniques.

4. Data Ownership and Control

  • There is ambiguity around who owns the data—individuals, data collectors, third-party vendors, or governments. This raises issues of data exploitation and unequal power dynamics.
Ethical Principles Involved:
  • Autonomy and property rights: Individuals should have a say in how their data is used and shared.
Best Practices:
  • Promote data sovereignty and user-centric data ownership models.
  • Provide users with access to their own data and allow data portability.
  • Compensate individuals when their data generates significant commercial value.

5. Transparency and Accountability

  • Algorithms and data analysis processes are often "black boxes," making it difficult for users or affected parties to understand how decisions are made.
Ethical Principles Involved:
  • Transparency: Data processes should be open and understandable.
  • Accountability: Entities must take responsibility for the consequences of data use.
Best Practices:
  • Maintain detailed documentation of algorithms and decision-making processes.
  • Implement explainable AI (XAI) techniques.
  • Establish regulatory bodies or ethics committees to oversee big data initiatives.

6. Security and Data Protection

  • Large datasets are attractive targets for cyberattacks, and breaches can expose sensitive personal or organizational information.
Ethical Principles Involved:
  • Non-maleficence: Prevent harm caused by data breaches or misuse.
Best Practices:
  • Use strong encryption and secure access protocols.
  • Conduct regular vulnerability assessments.
  • Train staff on data protection and ethical handling of information.

7. Dual-Use of Data

  • Data collected for one purpose may be repurposed for another, possibly harmful, use (e.g., surveillance, political manipulation, or discriminatory profiling).
Ethical Principles Involved:
  • Beneficence vs. non-maleficence: Use data to do good while avoiding misuse.
Best Practices:
  • Clearly define acceptable uses of data.
  • Monitor for potential misuse or mission creep.
  • Limit secondary use unless explicitly authorized.

8. Global and Cultural Sensitivities

  • What is considered ethical or private may vary across cultures and jurisdictions. Cross-border data flows may violate local ethical norms or regulations.
Ethical Principles Involved:
  • Respect for persons and cultural diversity.
Best Practices:
  • Comply with regional data protection laws.
  • Consult with local communities and stakeholders.
  • Customize data practices to respect cultural values and legal frameworks.
  • Big data analysis holds transformative potential, but it must be guided by strong ethical frameworks to avoid misuse, discrimination, and breaches of trust.
  • Organizations and data scientists must balance innovation with responsibility, implementing policies and practices that promote transparency, fairness, accountability, and respect for individual rights.