0Pricing
R Academy · Lesson

Topic Modeling with LDA

Discover latent topics in document corpora using the topicmodels package.

What Is Topic Modelling?

Topic modelling is an unsupervised machine learning technique that discovers latent thematic structure in a corpus. Latent Dirichlet Allocation (LDA) assumes each document is a mixture of K topics, and each topic is a probability distribution over words.

# LDA key assumptions:
# 1. Each document is a mixture of K topics
# 2. Each topic is a distribution over all vocabulary words
# 3. Words are generated by first picking a topic, then a word from that topic

# Example: K=2 topics in a corpus about tech and cooking
# Topic 1 (Tech):    neural(0.15) python(0.12) algorithm(0.10) ...
# Topic 2 (Cooking): recipe(0.14) flour(0.11) bake(0.10) ...

# A document about 'AI-generated recipes' might be:
# 70% Topic 1 (Tech) + 30% Topic 2 (Cooking)

cat('LDA parameters:\n')
cat('K = number of topics (you choose)\n')
cat('alpha = document-topic sparsity prior\n')
cat('beta  = topic-word sparsity prior\n')

DocumentTermMatrix from tm

LDA requires a Document-Term Matrix (DTM): rows are documents, columns are words, cells are word counts. The tm package's DocumentTermMatrix() or tidytext's cast_dtm() both produce this format.

library(tm)

# Build a corpus from raw text
docs <- c(
  'machine learning neural networks training algorithms',
  'deep learning gradient backpropagation optimizer',
  'python scikit numpy pandas machine learning',
  'database sql tables indexes queries joins',
  'relational schema normalization foreign primary',
  'nosql mongodb document store redis queries'
)

corpus <- Corpus(VectorSource(docs))
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, removeWords, stopwords('english'))
corpus <- tm_map(corpus, stripWhitespace)

dtm <- DocumentTermMatrix(corpus)
cat('DTM shape:', nrow(dtm), 'docs x', ncol(dtm), 'terms\n')
cat('Sparsity: ', round(tm::sparsity(dtm) * 100, 1), '%\n')

All lessons in this course

  1. Tokenization and Stop Word Removal
  2. TF-IDF and Term Frequency Analysis
  3. Sentiment Analysis in R
  4. Topic Modeling with LDA
← Back to R Academy