TTDS: Lab 7
Based on lectures 15 and 16 ("Comparing Corpora"). In this lab you compare two mystery corpora yourself: word by word, with mutual information and chi-square that you implement yourself, and topics by topic using LDA and BERTopic. The aim is not just to generate the list of top words but also to interpret them: what do they tell us about the corpora, and what do they not tell us?
SETUP
- Download and unzip the two mystery corpora.
- Each corpus contains posts from a single subcommunity on Reddit.com ("subreddit").
- The boundaries between posts are not marked in the files. You can split the contents on empty lines, treating each paragraph as a separate document. A paragraph is not always a complete Reddit post: a long post becomes several documents, and a quoted reply may become a document of its own. In this lab, "document" always means "paragraph", so keep that in mind when you interpret your results.
We recommend setting up a virtual environment for this lab instead of installing Python packages system-wide.
python3 -m venv ttds-lab6source ttds-lab6/bin/activate # Windows: ttds-lab6\Scripts\activatepip install numpy scipy gensim# for Part C only:pip install pandas scikit-learn umap-learn pyyaml packaging tqdmpip install --no-deps bertopic(
--no-depsavoids installing PyTorch: in Part C you use precomputed embeddings, so no embedding model is needed on your machine.)- Apply preprocessing: tokenization, stopping, case folding, stemming.
- You can reuse your lab 1 code.
- Remove any term that occurs fewer than 10 times in total across both corpora. Notice how this filter counts tokens (occurrences), but the tables in Part A count documents. These are different numbers.
PART A: WORD-LEVEL COMPARISONS
- Now you should find the most distinctive words, for each corpus as the target class (the other corpus is the non-target class).
- Write code in any programming language to compute Mutual Information (MI) and Chi-squared (X2) values for all words in each corpus.
- You can ignore words that appear less than 10 times overall.
- Hint: if you compute N00, N01, N11, and N10 (as described in the lecture) once for each word-corpus pair, you can use these numbers to quickly get both MI and χ².
- Zero cells: if one of the four counts is 0, the corresponding term of the MI sum is 0 (the limit of x log x as x → 0). Make sure your code returns a number in this case, not
nanor an error. - Test your functions on the two examples from lecture 15 before running them on the corpora: the export/poultry example (MI ≈ 0.00011, χ² ≈ 284) and the 80/20 example (term in 80 of 100 documents of A and 20 of 100 of B: MI ≈ 0.278 bits, χ² = 72).
- Produce a list of terms sorted by MI and by χ² for each corpus.
- Examine the top ten MI terms and top ten χ² terms for each corpus. Keep the four counts for each of these terms: you will need them in the discussion.
- Discuss with a friend:
- What differences do you notice between the two methods?
- Compare the top-ten list for corpus 1 with the top-ten list for corpus 2 (for the same method). What do you notice? Can you explain it from the formulas?
- For each term in your top-ten lists, look at its document rates in the two corpora (the fraction of each corpus's documents that contain it). Is the term more common or less common in the target corpus? Why can a term rank highly for a corpus in which it is rare?
- What did you learn about each corpus by analysing these lists? Pick two terms and read five documents containing each: does your interpretation survive?
- Apart from what the two communities are interested in, what else could produce some of these differences? (Think about how the data was sampled, dates, authors and bots, repeated or quoted text, document length, and your preprocessing.)
PART B: TOPIC-LEVEL COMPARISONS WITH LDA
- Train one LDA model with 10 topics on all documents from both corpora together, using gensim (see "Usage Examples": follow the steps in the first block of code).
- Your input is a list of all documents in this list-of-lists format, using your preprocessed tokens with stopwords removed:
[ ['this', 'is', 'a', 'sample', 'document'], ['this', 'is', 'another'] ] - Keep a separate list, in the same order, recording which corpus each document came from. The model does not need to know.
- Set
random_state(e.g. 0) andpasses(e.g. 10), and write them down, so that you can reproduce your run. - Why one model? Topics from two separately trained models are unrelated: "topic 3" in one model has nothing to do with "topic 3" in the other.
- Your input is a list of all documents in this list-of-lists format, using your preprocessed tokens with stopwords removed:
For every document, get its full topic distribution (all 10 probabilities):
theta = lda.get_document_topics(bow, minimum_probability=0) # list of (topic_id, probability), all topics
By default gensim leaves out small probabilities. If you then average only the values that were returned, your averages are wrong: a missing value means 0, not "skip this document".
- For each corpus, compute the overall topic probabilities by averaging the topic distributions of all documents in that corpus (10 numbers per corpus that sum to 1).
- Determine the top 3 topics for each corpus by overall probability, and view the top 10 words for each of these topics using print_topic().
- Read before you name: for each of these topics, find the 5 documents with the highest probability for that topic and read them. Only then give the topic a 1–3 word label.
- Stability: train a second model with a different
random_state(or with 15 topics). Match topics between the two runs by their words and documents, not by their topic numbers. Which of your conclusions survive the rerun? - Discuss with a friend:
- Do the two corpora share any of their top topics? Is that a problem, or a finding?
- Which topics have a substantial probability in both corpora, even if they are not in either corpus's top 3?
- What do the topics tell you that the MI/χ² lists did not, and vice versa?
PART C: BERTOPIC (about 30 minutes)
In lecture 16 we traced BERTopic's pipeline (embed → reduce → cluster → describe with c-TF-IDF) on 13 reviews. Here you run it on the mystery corpora. To keep the runtime short, the embeddings have been computed for you with the sentence-transformer all-MiniLM-L6-v2, for the same paragraph documents. BERTopic is not required in Coursework 2: this part is about understanding the pipeline, so don't spend more than about 30 minutes on it.
Download the lab 7 part C zip file and unzip, about 140 MB on disk.
In your lab virtual environment (Python 3.10–3.13; Windows, macOS or Linux), install what it needs (see above for
pip installcommands), then run it:python lab6_bertopic_starter.pyA run should take about 2–3 minutes for the ~70,000 paragraphs, plus up to a minute the first time, and needs about 1 GB of memory. Results can differ slightly between computers, even with the same
--seed, so your topic numbers may not match your neighbour's.- Trace the stages. The script prints the output of each stage. How many dimensions do the embeddings have, and after reduction? How many topics were found, and what fraction of documents are outliers (topic −1)?
- One topic in detail. Pick a topic (
--topic N). Look at its top words and read its representative documents, then give it a label. The script also prints the numbers you need to compute the c-TF-IDF weight of one of its words by hand (--word w), using the formula from lecture 16. Check your result against BERTopic's value. (BERTopic removes punctuation before counting words, and the counts the script prints do the same.) - Outliers. Read some of the outlier documents. Why might they be outliers? Is the outlier rate the same for both corpora?
- Compare with LDA. The script prints the share of each corpus's documents in each topic, with and without the outliers in the denominator. Which BERTopic topics correspond to LDA topics from Part B, and is anything new? How is "share of documents in a cluster" different from LDA's "average topic probability"? For these short paragraphs, which model's topics do you find easier to interpret, and why?
- If you have time: rerun with a different
--min-cluster-size(e.g. 50 and 300) or--seed, and see how the number of topics and the outlier rate change.
IF YOU HAVE EXTRA TIME
- Try changing the number of LDA topics and running LDA again to see what happens, or create a visualisation of your topics using pyLDAvis.
- For your top MI terms, compute a signed measure (for example the difference in document rates, or a smoothed log ratio) and compare the two rankings.
Note: The text analysis part of Coursework 2 uses three corpora and 20 LDA topics, but the same methods. You can share findings about the lab data with other students; don't share anything about the coursework data.