{ "cells": [ { "cell_type": "markdown", "id": "nli-title", "metadata": {}, "source": "# W10 Lab: zero-shot stance detection with NLI\n\nA short companion to the integrated Week 10 guide. Adapted from Michael Burnham's official zero-shot stance tutorial using three constructed classroom texts.\n" }, { "cell_type": "markdown", "id": "nli-goal", "metadata": {}, "source": "## What changes from supervised classification?\n\nThe earlier Flair and Transformers notebooks learn environmental-policy labels from human-coded training examples. This exercise instead reuses a Transformer already trained on natural language inference (NLI). We supply the stance meanings as complete hypotheses. This is a separate Trump stance task: the environmental-policy classifier's outputs cannot simply be renamed.\n\nYou can run this notebook independently, without fitting either policy model.\n" }, { "cell_type": "markdown", "id": "nli-environment", "metadata": {}, "source": "## Packages and device\n\nUse the prepared Python environment with `torch`, `transformers`, `pandas` and `sentencepiece`. In a fresh notebook environment, run the following installation command once in the active kernel, then restart it:\n\n```python\n%pip install torch transformers pandas sentencepiece\n```\n\nThe model-loading cell may download a large checkpoint. This demonstration explicitly uses CPU (`device=-1`), so it can take time. The author's [Colab tutorial](https://colab.research.google.com/drive/1YLmI2WMkIVpgeUobgMDVXkjf8JfbRxvW?usp=sharing) is another way to follow the example.\n" }, { "cell_type": "code", "id": "nli-imports", "metadata": {}, "execution_count": null, "outputs": [], "source": "import pandas as pd\nimport torch\nfrom transformers import pipeline\n" }, { "cell_type": "markdown", "id": "nli-load-explain", "metadata": {}, "source": "## N1. Load an existing NLI model\n\n`pipeline(\"zero-shot-classification\", ...)` uses a model trained to recognize relations between a text and a hypothesis. Loading this checkpoint does not train a new Trump stance classifier. Keep its complete model ID with your results.\n\nThe checkpoint revision is pinned to the displayed CPU demonstration. Explicit float32 precision and batch size one match that run.\n" }, { "cell_type": "code", "id": "nli-load", "metadata": {}, "execution_count": null, "outputs": [], "source": "nli_model_id = (\n \"MoritzLaurer/\"\n \"DeBERTa-v3-large-mnli-fever-anli-ling-wanli\"\n)\nnli_revision = \"b3546ea6b0346eb6f8d5d68b13c7dc6d0376b3d7\"\nnli_classifier = pipeline(\n \"zero-shot-classification\",\n model=nli_model_id,\n revision=nli_revision,\n device=-1,\n torch_dtype=torch.float32,\n batch_size=1,\n)\n" }, { "cell_type": "markdown", "id": "nli-load-check", "metadata": {}, "source": "**Check:** which earlier call updated the policy classifier's weights? Why is there no `Trainer` or `.train()` call here? Zero-shot means no target-task parameter updates in this exercise; the NLI model has already been trained.\n" }, { "cell_type": "markdown", "id": "nli-hypotheses-explain", "metadata": {}, "source": "## N2. Make the target and categories explicit\n\nThe template supplies the target, Trump. Each candidate fills the blank to create a complete hypothesis. Print these statements before looking at predictions.\n" }, { "cell_type": "code", "id": "nli-hypotheses", "metadata": {}, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": " candidate hypothesis\n supports The author of this tweet supports Trump.\n opposes The author of this tweet opposes Trump.\ndoes not express an opinion about The author of this tweet does not express an opinion about Trump.\n" } ], "source": "nli_labels = [\n \"supports\",\n \"opposes\",\n \"does not express an opinion about\",\n]\nnli_template = \"The author of this tweet {} Trump.\"\n\nnli_hypotheses = pd.DataFrame({\n \"candidate\": nli_labels,\n \"hypothesis\": [\n nli_template.format(label)\n for label in nli_labels\n ],\n})\nprint(nli_hypotheses.to_string(index=False))\n" }, { "cell_type": "markdown", "id": "nli-hypotheses-read", "metadata": {}, "source": "**Read the constructed hypotheses:**\n\n| Candidate | Complete hypothesis |\n|---|---|\n| supports | The author of this tweet supports Trump. |\n| opposes | The author of this tweet opposes Trump. |\n| does not express an opinion about | The author of this tweet does not express an opinion about Trump. |\n\nThe model will pair each text with all three statements. These strings are inputs we chose, not labels or explanations generated by the model.\n\n**Check:** what would need to change to study stance toward a bill?\n" }, { "cell_type": "markdown", "id": "nli-examples-explain", "metadata": {}, "source": "## N3. Read three texts before running the classifier\n\nTexts A and B explicitly support or oppose Trump's policies. Text C states a meeting time without expressing a stance toward Trump. The `reading_key` records our intended reading of a constructed example. It is not a human annotation from a research corpus, and these three texts are not an accuracy benchmark.\n" }, { "cell_type": "code", "id": "nli-examples", "metadata": {}, "execution_count": null, "outputs": [], "source": "nli_texts = [\n \"I support Trump's policies.\",\n \"I oppose Trump's policies.\",\n \"The committee meets on Tuesday.\",\n]\nnli_examples = pd.DataFrame({\n \"example\": [\"A\", \"B\", \"C\"],\n \"text\": nli_texts,\n \"reading_key\": [\n \"supports\",\n \"opposes\",\n \"does not express an opinion about\",\n ],\n})\n" }, { "cell_type": "markdown", "id": "nli-classify-explain", "metadata": {}, "source": "Pair the texts with the candidate hypotheses. `multi_label=False` ranks the candidates as mutually exclusive stance choices for each text. The same input text is evaluated against each complete hypothesis.\n" }, { "cell_type": "code", "id": "nli-classify", "metadata": {}, "execution_count": null, "outputs": [], "source": "nli_results = nli_classifier(\n nli_texts,\n candidate_labels=nli_labels,\n hypothesis_template=nli_template,\n multi_label=False,\n)\n" }, { "cell_type": "markdown", "id": "nli-table-explain", "metadata": {}, "source": "## Keep scores attached to candidate names\n\nThe pipeline returns candidates in score order, which can differ by text. Convert each returned label-score pair to a dictionary before making a table. Print the full text, reading key, predicted stance and all three scores.\n" }, { "cell_type": "code", "id": "nli-table", "metadata": {}, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": "example text reading_key predicted_stance supports opposes does not express an opinion about\n A I support Trump's policies. supports supports 0.991822 0.004377 0.003801\n B I oppose Trump's policies. opposes opposes 0.008588 0.984321 0.007091\n C The committee meets on Tuesday. does not express an opinion about does not express an opinion about 0.206294 0.196707 0.597000\n" } ], "source": "nli_rows = []\nfor example, result in zip(\n nli_examples.to_dict(\"records\"), nli_results\n):\n scores = dict(zip(result[\"labels\"], result[\"scores\"]))\n nli_rows.append({\n **example,\n \"predicted_stance\": result[\"labels\"][0],\n **{label: scores[label] for label in nli_labels},\n })\nnli_table = pd.DataFrame(nli_rows)\nprint(nli_table.to_string(\n index=False,\n float_format=lambda value: f\"{value:.6f}\",\n))\n" }, { "cell_type": "markdown", "id": "nli-read-predictions", "metadata": {}, "source": "**Executed demonstration · 27 November 2026**\n\nThe saved table output comes from a real CPU inference run with PyTorch 2.2.2, Transformers 4.54.0 and the pinned checkpoint revision. No target-task training occurred. The code cells start without execution counters; rerun them to generate your own outputs. The saved printout records the dated demonstration, not a new research validation set.\n\nRead A, then B, then C. Explain each top label using the text. A receives supports at .991822; B receives opposes at .984321. C receives the no-opinion candidate at .597000, with supports at .206294 and opposes at .196707. The winning candidate is not certainty. The reading keys are constructed teaching interpretations, not annotations from a research corpus.\n\nWith `multi_label=False`, the pipeline normalizes candidate entailment logits across the candidate set. These scores are **not accuracy** and are **not the full entailment/neutral/contradiction distribution**. Changing the candidates can change the scores. The explicit “does not express an opinion” stance is different from NLI `neutral`, which means a particular hypothesis remains unresolved by its text.\n\n[Read the complete executed printout](../results/burnham-nli-demo.txt).\n" }, { "cell_type": "markdown", "id": "nli-compare", "metadata": {}, "source": "## N4. Compare the workflows\n\n| Question | Earlier supervised classification | This zero-shot NLI exercise |\n|---|---|---|\n| Input | Policy excerpt | Text paired with complete stance hypotheses |\n| Research labels | Human labels train a task-specific classifier | Category meanings are written as hypotheses |\n| Weight updates | The training call updates weights | The existing NLI checkpoint is reused |\n| Validation | Evaluate predictions on held-out labeled texts | Evaluate hypotheses and the decision rule on target-task human labels |\n\nBoth use Transformers. NLI models can also be fine-tuned; this exercise uses one without target-task updates. The three classroom examples do not validate a research measure.\n" }, { "cell_type": "markdown", "id": "nli-submit", "metadata": {}, "source": "## Check and submit\n\nSubmit the printed three-text table and explain one prediction. Propose one alternative hypothesis wording and describe how you would test its effect on separately human-coded target texts.\n\n1. Why is the hypothesis part of the input?\n2. Why cannot policy categories simply be renamed as stance categories?\n3. How does the “does not express an opinion” candidate differ from NLI `neutral`?\n4. What evidence would you need before applying these hypotheses to a research corpus?\n" }, { "cell_type": "markdown", "id": "nli-sources", "metadata": {}, "source": "## Sources\n\n- [Integrated Week 10 Lab guide](../Lab_Session_W10.html#nli-demo)\n- [Burnham's official zero-shot notebook](https://github.com/MLBurnham/stance_detection_tutorials/blob/main/Zero-shot_stance_detection.ipynb)\n- [Official Colab](https://colab.research.google.com/drive/1YLmI2WMkIVpgeUobgMDVXkjf8JfbRxvW?usp=sharing)\n- [DeBERTa-v3-large NLI model card](https://huggingface.co/MoritzLaurer/DeBERTa-v3-large-mnli-fever-anli-ling-wanli)\n- [Hugging Face ZeroShotClassificationPipeline](https://huggingface.co/docs/transformers/en/main_classes/pipelines#transformers.ZeroShotClassificationPipeline)\n\nThe tutorial demonstrates Trump stance. Burnham's paper separately applies topic-matched hypotheses to COVID-19 tweets. This small notebook does not reproduce that full analysis.\n" } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" }, "w10_demo_output": { "executed_on": "2026-11-27", "model_id": "MoritzLaurer/DeBERTa-v3-large-mnli-fever-anli-ling-wanli", "revision": "b3546ea6b0346eb6f8d5d68b13c7dc6d0376b3d7", "device": "cpu", "torch_dtype": "float32", "target_task_fine_tuning": false, "source": "../results/burnham-nli-demo.txt", "note": "Saved printouts use the dated verified inference; rerun notebook cells for your own output." } }, "nbformat": 4, "nbformat_minor": 5 }