TTDS: Lab 8

Based on lectures 17 and 18 ("Text Classification" 1 and 2).

In this lab you will build, evaluate and improve a classifier that sorts tweets into 14 categories, following the same protocol you will use in Coursework 2: make every choice on a development set, and use the test set once, at the end.

Your starting point is the notebook from lecture 18. It already does the whole pipeline: it splits off a development set, builds the vocabulary, turns tweets into bag-of-words vectors, trains an SVM, evaluates it, compares it with a pretrained model, and runs the test set once at the end. You don't need to rewrite any of that. First make sure you understand what each part does and why (part 1), then check the evaluation yourself (part 2), and only then try to improve on it (parts 3 and 4).

SETUP: THE LECTURE 18 NOTEBOOK

Option 1: Run it in Noteable

Follow the link in Learn to run the Jupyter notebook for Lecture 18 on Noteable, the University's hosted platform for computational notebooks.

You'll find the notebook in the shared folder for instructors and students, and you'll need to copy it out of the folder so you can edit and run it. Make sure to copy the data out of the folder as well, so the notebook can see the data.

Option 2: Run it on your own machine

  • Create a conda environment with everything the lab needs (on Windows, run these commands in the Anaconda Prompt):
    conda create -n ttds-lab8 -c conda-forge python=3.12 numpy scipy scikit-learn jupyterlab ipywidgets sentence-transformers google-genai
    conda activate ttds-lab8
    jupyter lab
    (sentence-transformers is for the pretrained model in section 10; it also installs PyTorch (several hundred MB), and the first run downloads a 90 MB model. google-genai is only needed for the optional sections 11–12.)
  • Download the notebook and data ZIP file and extract it. The zip file contains:
    • Tweets.14cat.train: 2,503 tweets. The notebook splits these into a training split and a development split.
    • Tweets.14cat.test: 625 tweets for the final test.
    • Both are tab separated: tweet_ID tweet category
  • Make a copy of the notebook for your own changes, so you can always go back to the original. Make sure the copy is in the same folder as the files.

PART 1: UNDERSTAND THE NOTEBOOK

Run the notebook from the top, up to and including section 10, and read each section as you go. Answer these questions before you change anything. Each one points to the section where you'll find the answer.

  • Section 3b, the development split. What fraction of the training file becomes the development split? Why is the split stratified, and why is the seed fixed? The notebook says a random split answers "how well do we do on more tweets like these?". What kind of split would you need to claim that the classifier works for new users, or for next year's tweets?
  • Section 4, the vocabulary. Which tweets is the vocabulary built from: the training split, the development split, or the test file? What would be wrong with building it from all of them? Why are the words sorted before they get IDs?
  • Section 5, bag of words. What happens to a word in a development tweet that never occurred in the training split? Why does the matrix have one more column than the vocabulary has words?
  • Sections 6–7, training. Why is the accuracy on the training split 1.0, and why doesn't that tell you anything about new tweets? Which value of C does the notebook use, and on which data would you choose a better one?
  • Section 8, development results. Compare the SVM with the majority-class baseline and the random forest. Why is the baseline's macro-F1 so much lower than its accuracy? Which categories are easiest and hardest?
  • Section 8, errors. Look at the most frequent confusions and read the misclassified tweets the notebook prints (print more if you like). Which errors are the model's fault, and which come from the labels themselves? These labels come from the YouTube category of a video linked in the tweet. And is a tweet about a football video game "Gaming" or "Sports"?
  • Section 10, the pretrained comparator. What is trained here and what stays fixed? How does it do compared with the SVM, and how long does it take?
  • Section 13 (read it, don't run it yet). When does the notebook use the test file, and how does it decide which model to evaluate on it?

PART 2: CHECK THE EVALUATION YOURSELF

  • The notebook's report function and scikit-learn's classification_report compute the scores for you. Write your own function that takes the list of predicted category IDs and the list of correct category IDs, and returns:
    • accuracy;
    • precision, recall and F1 for each class, and the number of correct examples of each class (the "support");
    • macro-averaged precision, recall and F1: the arithmetic mean of the per-class values, as in lecture 17.
  • Zero division: if a class is never predicted, its precision is 0/0; if a class has no examples, its recall is 0/0. Define both as 0, and still include that class in the macro average. This matches lecture 17's majority-class example and zero_division=0 in scikit-learn.
  • Check that the two lists have the same length before you compute anything: a silent mismatch gives meaningless numbers.
  • Run your function on the SVM's development predictions and on the majority-class baseline, and check that you get the same numbers as the notebook. If you don't, find out why.

PART 3: IMPROVE ON THE BASELINE

Now try to build a better system. You can go in any direction. Start from what you learned about the errors in part 1, and make one change at a time, so that you know which change made the difference. Some directions:

  • Better features for the bag of words. Stemming and stopping; keeping hashtags as separate features (the tokeniser currently removes the "#"); word bigrams, so that "not good" becomes a feature (this matters a lot for sentiment in Coursework 2); TF-IDF values instead of counts; keeping only the top-N features by MI or χ² (lecture 15); non-textual features such as tweet length or the presence of links and emojis (scale them; see lecture 17).
  • Other classifiers. Any scikit-learn classifier: logistic regression, naive Bayes, a linear SVM with a different C, k-nearest neighbours, gradient boosting, … Tune their settings on the development split.
  • Other representations. A different sentence-transformers model instead of all-MiniLM-L6-v2 (the pretrained models list compares speed and quality), a different classifier on top of the embeddings, or embeddings and bag-of-words features combined.
  • Prompting. Other Gemini models, other label wordings or category descriptions, other few-shot examples, or a different number of them. This needs your own API key, so read the instructions in section 11 first. Each change means new calls to the model, so stay on the notebook's sample of development tweets.
  • (Advanced) Fine-tuning a Hugging Face model for sequence classification, as described here: https://huggingface.co/docs/transformers/tasks/sequence_classification. It's not required in the coursework, and it is slow without a GPU (Noteable doesn't have a GPU).

Whatever you try, keep to the notebook's rules:

  • Anything computed from data (a vocabulary, IDF values, MI or χ² scores, a scaler, classifier weights, few-shot examples) comes from the training split only.
  • Every choice (features, model, settings, prompt, parsing rule) is made on the development split, and every system you compare is scored on the same development tweets.
  • Record what each system costs as well as how well it does: training time, prediction time and, for prompting, the number of calls.

For each change, ask: did it fix the errors that motivated it? Did macro-F1 improve, and did any class get worse?

PART 4: COMPARE, THEN TEST ONCE

  • Find one development tweet that your best system gets right and the baseline SVM gets wrong, and one the other way round. What do they tell you about the two systems?
  • Add your best system to the comparison in section 13, and choose by development macro-F1. Only then run the final cell, which evaluates the chosen system on the test set, once. If the test results are noticeably different from the development results, why might that be?

NOTE

Parts of this lab are similar to part 3 of Coursework 2 (though Coursework 2 is three-way sentiment classification on a different dataset, with a different file format), so please try to finish it properly. You can share results and findings about the lab data with other students. Just make sure not to share anything about the coursework data.

License
All rights reserved The University of Edinburgh