{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "X4cRE8IbIrIV" }, "source": [ "If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets as well as other dependencies. Uncomment the following cell and run it. Note the `rouge-score` and `nltk` dependencies - even if you've used 🤗 Transformers before, you may not have these installed!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 1000 }, "id": "MOsHUjgdIrIW", "outputId": "f84a093e-147f-470e-aad9-80fb51193c8e" }, "outputs": [], "source": [ "#! pip install transformers datasets\n", "#! pip install rouge-score nltk\n", "#! pip install huggingface_hub" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you're opening this notebook locally, make sure your environment has an install from the last version of those libraries.\n", "\n", "To be able to share your model with the community and generate results like the one shown in the picture below via the inference API, there are a few more steps to follow.\n", "\n", "First you have to store your authentication token from the Hugging Face website (sign up [here](https://huggingface.co/join) if you haven't already!) then run the following cell and input your token:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from huggingface_hub import notebook_login\n", "\n", "notebook_login()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then you need to install Git-LFS and setup Git if you haven't already. Uncomment the following instructions and adapt with your name and email:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# !apt install git-lfs\n", "# !git config --global user.email \"you@example.com\"\n", "# !git config --global user.name \"Your Name\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Make sure your version of Transformers is at least 4.16.0 since some of the functionality we use was introduced in that version:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4.21.0.dev0\n" ] } ], "source": [ "import transformers\n", "\n", "print(transformers.__version__)" ] }, { "cell_type": "markdown", "metadata": { "id": "HFASsisvIrIb" }, "source": [ "You can find a script version of this notebook to fine-tune your model in a distributed fashion using multiple GPUs or TPUs [here](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We also quickly upload some telemetry - this tells us which examples and software versions are getting used so we know where to prioritize our maintenance efforts. We don't collect (or care about) any personally identifiable information, but if you'd prefer not to be counted, feel free to skip this step or delete this cell entirely." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers.utils import send_example_telemetry\n", "\n", "send_example_telemetry(\"summarization_notebook\", framework=\"tensorflow\")" ] }, { "cell_type": "markdown", "metadata": { "id": "rEJBSTyZIrIb" }, "source": [ "# Fine-tuning a model on a summarization task" ] }, { "cell_type": "markdown", "metadata": { "id": "kTCFado4IrIc" }, "source": [ "In this notebook, we will see how to fine-tune one of the [🤗 Transformers](https://github.com/huggingface/transformers) model for a summarization task. We will use the [XSum dataset](https://arxiv.org/pdf/1808.08745.pdf) (for extreme summarization) which contains BBC articles accompanied with single-sentence summaries.\n", "\n", "![Widget inference on a summarization task](images/summarization.png)\n", "\n", "We will see how to easily load the dataset for this task using 🤗 Datasets and how to fine-tune a model on it using Keras." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "model_checkpoint = \"t5-small\"" ] }, { "cell_type": "markdown", "metadata": { "id": "4RRkXuteIrIh" }, "source": [ "This notebook is built to run with any model checkpoint from the [Model Hub](https://huggingface.co/models) as long as that model has a sequence-to-sequence version in the Transformers library. Here we pick the [`t5-small`](https://huggingface.co/t5-small) checkpoint. " ] }, { "cell_type": "markdown", "metadata": { "id": "whPRbBNbIrIl" }, "source": [ "## Loading the dataset" ] }, { "cell_type": "markdown", "metadata": { "id": "W7QYTpxXIrIl" }, "source": [ "We will use the [🤗 Datasets](https://github.com/huggingface/datasets) library to download the data and get the metric we need to use for evaluation (to compare our model to the benchmark). This can be easily done with the functions `load_dataset` and `load_metric`. " ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "id": "IreSlFmlIrIm" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Using custom data configuration default\n", "Reusing dataset xsum (/home/matt/.cache/huggingface/datasets/xsum/default/1.2.0/32c23220eadddb1149b16ed2e9430a05293768cfffbdfd151058697d4c11f934)\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "060b5fe0604e4646aee58b876ad50d70", "version_major": 2, "version_minor": 0 }, "text/plain": [ " 0%| | 0/3 [00:00, ?it/s]" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from datasets import load_dataset, load_metric\n", "\n", "raw_datasets = load_dataset(\"xsum\")\n", "metric = load_metric(\"rouge\")" ] }, { "cell_type": "markdown", "metadata": { "id": "RzfPtOMoIrIu" }, "source": [ "The `dataset` object itself is [`DatasetDict`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasetdict), which contains one key for the training, validation and test set:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "id": "GWiVUF0jIrIv", "outputId": "35e3ea43-f397-4a54-c90c-f2cf8d36873e" }, "outputs": [ { "data": { "text/plain": [ "DatasetDict({\n", " train: Dataset({\n", " features: ['document', 'summary', 'id'],\n", " num_rows: 204045\n", " })\n", " validation: Dataset({\n", " features: ['document', 'summary', 'id'],\n", " num_rows: 11332\n", " })\n", " test: Dataset({\n", " features: ['document', 'summary', 'id'],\n", " num_rows: 11334\n", " })\n", "})" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "raw_datasets" ] }, { "cell_type": "markdown", "metadata": { "id": "u3EtYfeHIrIz" }, "source": [ "To access an actual element, you need to select a split first, then give an index:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "id": "X6HrpprwIrIz", "outputId": "d7670bc0-42e4-4c09-8a6a-5c018ded7d95" }, "outputs": [ { "data": { "text/plain": [ "{'document': 'The full cost of damage in Newton Stewart, one of the areas worst affected, is still being assessed.\\nRepair work is ongoing in Hawick and many roads in Peeblesshire remain badly affected by standing water.\\nTrains on the west coast mainline face disruption due to damage at the Lamington Viaduct.\\nMany businesses and householders were affected by flooding in Newton Stewart after the River Cree overflowed into the town.\\nFirst Minister Nicola Sturgeon visited the area to inspect the damage.\\nThe waters breached a retaining wall, flooding many commercial properties on Victoria Street - the main shopping thoroughfare.\\nJeanette Tate, who owns the Cinnamon Cafe which was badly affected, said she could not fault the multi-agency response once the flood hit.\\nHowever, she said more preventative work could have been carried out to ensure the retaining wall did not fail.\\n\"It is difficult but I do think there is so much publicity for Dumfries and the Nith - and I totally appreciate that - but it is almost like we\\'re neglected or forgotten,\" she said.\\n\"That may not be true but it is perhaps my perspective over the last few days.\\n\"Why were you not ready to help us a bit more when the warning and the alarm alerts had gone out?\"\\nMeanwhile, a flood alert remains in place across the Borders because of the constant rain.\\nPeebles was badly hit by problems, sparking calls to introduce more defences in the area.\\nScottish Borders Council has put a list on its website of the roads worst affected and drivers have been urged not to ignore closure signs.\\nThe Labour Party\\'s deputy Scottish leader Alex Rowley was in Hawick on Monday to see the situation first hand.\\nHe said it was important to get the flood protection plan right but backed calls to speed up the process.\\n\"I was quite taken aback by the amount of damage that has been done,\" he said.\\n\"Obviously it is heart-breaking for people who have been forced out of their homes and the impact on businesses.\"\\nHe said it was important that \"immediate steps\" were taken to protect the areas most vulnerable and a clear timetable put in place for flood prevention plans.\\nHave you been affected by flooding in Dumfries and Galloway or the Borders? Tell us about your experience of the situation and how it was handled. Email us on selkirk.news@bbc.co.uk or dumfries@bbc.co.uk.',\n", " 'summary': 'Clean-up operations are continuing across the Scottish Borders and Dumfries and Galloway after flooding caused by Storm Frank.',\n", " 'id': '35232142'}" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "raw_datasets[\"train\"][0]" ] }, { "cell_type": "markdown", "metadata": { "id": "WHUmphG3IrI3" }, "source": [ "To get a sense of what the data looks like, the following function will show some examples picked randomly in the dataset." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "id": "i3j8APAoIrI3" }, "outputs": [], "source": [ "import datasets\n", "import random\n", "import pandas as pd\n", "from IPython.display import display, HTML\n", "\n", "\n", "def show_random_elements(dataset, num_examples=5):\n", " assert num_examples <= len(\n", " dataset\n", " ), \"Can't pick more elements than there are in the dataset.\"\n", " picks = []\n", " for _ in range(num_examples):\n", " pick = random.randint(0, len(dataset) - 1)\n", " while pick in picks:\n", " pick = random.randint(0, len(dataset) - 1)\n", " picks.append(pick)\n", "\n", " df = pd.DataFrame(dataset[picks])\n", " for column, typ in dataset.features.items():\n", " if isinstance(typ, datasets.ClassLabel):\n", " df[column] = df[column].transform(lambda i: typ.names[i])\n", " display(HTML(df.to_html()))" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "id": "SZy5tRB_IrI7", "outputId": "ba8f2124-e485-488f-8c0c-254f34f24f13" }, "outputs": [ { "data": { "text/html": [ "
\n", " | document | \n", "summary | \n", "id | \n", "
---|---|---|---|
0 | \n", "South Wales Police alleged Detective Sergeant Andrew Whelan failed to investigate Crimestoppers and witness complaints about Watkins in 2010.\\nWatkins was sentenced to 35 years in 2013 after admitting a string of child sex offences.\\nA tribunal panel found it \"inappropriate\" to make any findings of misconduct against the officer.\\nDet Sgt Whelan was accused of failing to act on information about Watkins given to Crimestoppers three times between March and October 2010.\\nJonathan Walters, for South Wales Police, told the tribunal: \"You failed to take any action in relation to those logs.\"\\nThe second allegation was that Det Sgt Whelan failed to react to a complaint from an unnamed member of the public in October 2010 that Watkins had \"child pornography on his computer and that he fantasised about abusing children\".\\nJohn Beggs QC, representing Det Sgt Whelan, described him as an \"exemplary officer\", who was dedicated to his duty and had an \"unblemished\" 25-year career.\\n\"He had six years of unrelenting hell where he worked many more hours than he was being paid, and was frequently working 18 hour days,\" he said.\\n\"This was an isolated out-of-character incident in difficult circumstances.\"\\nTribunal panel chairman Robert Vernon said: \"It was an uncharacteristic lapse of judgement from an officer who was otherwise carrying out his duties in a diligent and professional manner.\\n\"It was a decision taken in very difficult circumstances, bearing in mind his workload and professional and personal circumstances at that time.\" | \n", "A detective who investigated paedophile Lostprophets singer Ian Watkins has been cleared of misconduct. | \n", "39862615 | \n", "
1 | \n", "Extensive discussions between leading Fleet Street executives over the past several months have been aimed at combating the structural decline of the market, as annual display advertising diminishes by around 20% and circulations continue their downward trajectory.\\nThe talks have been hampered by personality clashes, the competing priorities of different groups, and the sheer novelty of companies whose commercial operations had hitherto been aggressive rivals, trying instead to co-operate for mutual advantage.\\nProject Rio will continue, with News UK, Telegraph Media Group, and the owner of The Guardian still trying to collaborate.\\nDMGT, the publisher of the Daily Mail, pulled out of Project Rio in January, saying it had \"stepped back\" to pursue \"broader commercial priorities\" in 2017. These include the monetisation of Mail Online, which has expanded quickly into America and is a priority of Paul Zwillenberg, chief executive of DMGT.\\nOn 10 January I revealed that Trinity was in talks with Northern & Shell, the newspaper group run by Richard Desmond, and David Montgomery, the former newspaper executive and investor, about back-office consolidations.\\nMy recent conversations with very senior sources in the industry make clear that the failure to progress this work on consolidation, which could potentially reap huge savings, is a source of immense frustration to the parties involved.\\nFor Trinity, focusing on that consolidation is a higher priority than Project Rio.\\nBut with the flight of advertising from print to digital accelerating, and Facebook and Google tightening their grip on that money, newspapers are struggling to make enough money from their websites to offset the loss of money from print, due to structural decline.\\nEven after the closure of the print Independent (of which I was editor) last year, Britain's newspaper sector is very full - and arguably over-supplied - for a country with our population size.\\nAs this blog has repeatedly argued, bloated sectors facing structural decline are bound to consolidate. For Fleet Street, it's a question not of when, but how.\\nI've been sent a statement on behalf of Telegraph Media Group, Guardian Media Group and News UK.\\nIt says: \"Telegraph Media Group, Guardian Media Group and News UK today confirmed their continued commitment to working together to significantly improve the commercial value and perception of the news brands in the UK.\\n\"Trinity Mirror have confirmed that they will step aside from involvement in the next phase of the project, whilst wishing it well and reserving an option to rejoin at a later stage.\\n\"The three partners are working with market-leading consultancies on building the right approach to ensure that the industry continues to evolve to service key client and agency needs.\" | \n", "I can reveal that Trinity Mirror, publisher of the Mirror titles, has pulled out of talks to create a joint advertising initiative across Britain's national newspaper industry. | \n", "39081377 | \n", "
2 | \n", "The pair are both available for Saturday's FA Cup quarter-final against 12-times winners Arsenal.\\nCalder, 21, spent the first half of the season on loan at Doncaster, scoring once in 20 appearances.\\nEtheridge, 22, started his career at Derby and has made eight appearances for the League Two leaders this season. | \n", "Lincoln City have signed Aston Villa midfielder Riccardo Calder and Doncaster goalkeeper Ross Etheridge on loan until the end of the season. | \n", "39233337 | \n", "
3 | \n", "Westbound traffic has been diverted via the A48 Southern Distributor Road between M4 junctions 24 and 28.\\nThe westbound carriageway, between Junction 25a and Junction 26 of the M4, will reopen at 06:00 BST on Monday.\\nMotorists have been warned there is \"stop-start traffic\" on M4 Westbound between the Coldra (junction 24) and Caerleon (junction 25).\\nInrix traffic sensors are also showing slow traffic on the A48 Southern Distributor Road to the south of Newport.\\nBoth tunnels will be closed during the night occasionally as engineers upgrade the mechanical and electrical systems.\\nScheduled weekend closures for the Brynglas Tunnels on the M4:\\nWestbound:\\nEastbound: | \n", "The westbound side of the M4's Brynglas Tunnels at Newport is closed on Sunday as its 18-month upgrade continues. | \n", "40317857 | \n", "
4 | \n", "The 28-year-old former Salisbury player joined Rovers in 2014 and has since made 20 first-team appearances.\\nHe played in the promotion final win against Grimsby which earned Rovers promotion back to the Football League.\\nPuddy joins Braintree, 22nd in non-league's top flight, as competition for Sam Beasant.\\nFind all the latest football transfers on our dedicated page. | \n", "National League side Braintree Town have signed goalkeeper Will Puddy on a one-month loan deal from League One club Bristol Rovers. | \n", "37455713 | \n", "