{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import pandas as pd\n", "import os, json\n", "from transformers import pipeline\n", "from tqdm import tqdm" ] }, { "cell_type": "markdown", "source": [ "## Load the dataset" ], "metadata": { "collapsed": false } }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [ "from datasets import load_dataset\n", "\n", "dataset = load_dataset(\"generative-newsai/news-unmasked\")\n", "\n", "# Train and test split\n", "test_dataset = dataset[\"test\"]\n" ], "metadata": { "collapsed": false, "pycharm": { "is_executing": true } } }, { "cell_type": "markdown", "source": [ "## Check first 5 rows of the Test dataset" ], "metadata": { "collapsed": false } }, { "cell_type": "code", "execution_count": 3, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'image': [, , , , ], 'section': ['Television', 'Sports', 'Television', 'Technology', 'Fashion & Style'], 'headline': [\"What 's on TV Monday : ' The Voice ' and ' Gentefied '\", 'Phillies - Blue Jays Games Postponed After 2 Staff Members Test [MASK]', \"Joe Biden 's Run Has [MASK] Night Looking for a Fight\", 'Pinterest Posts [MASK] Loss , but Falls Short of Wall St. Estimates', 'Yolanda Foster : Watching Her Daughter Gigi Hadid From the Front Row'], 'image_id': ['00008455-a932-5f2c-b5ce-86584d8345b0', '00040f12-c19e-54db-9513-d4a3d9ce30f1', '0006d6e6-a16f-5d69-a307-0e7e1b659075', '000755c6-df96-502a-a3e4-8f78f0919a8c', '001b8cc1-c623-571c-9e2d-86e1f3f7c20c']}\n" ] } ], "source": [ "# Check first 5 rows of the test dataset\n", "sample_data = test_dataset[:5]\n", "print(sample_data)" ], "metadata": { "collapsed": false } }, { "cell_type": "markdown", "source": [ "## Load the model" ], "metadata": { "collapsed": false } }, { "cell_type": "code", "execution_count": 5, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Some weights of the model checkpoint at mlcorelib/deberta-base-uncased were not used when initializing BertForMaskedLM: ['cls.seq_relationship.bias', 'cls.seq_relationship.weight']\n", "- This IS expected if you are initializing BertForMaskedLM from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n", "- This IS NOT expected if you are initializing BertForMaskedLM from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n" ] } ], "source": [ "model_name = \"mlcorelib/deberta-base-uncased\"\n", "unmasker = pipeline('fill-mask', model=model_name)" ], "metadata": { "collapsed": false } }, { "cell_type": "markdown", "source": [ "## Unmask the sentences" ], "metadata": { "collapsed": false } }, { "cell_type": "code", "execution_count": 6, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 12247/12247 [05:47<00:00, 35.20it/s]\n" ] } ], "source": [ "all_masked_words = []\n", "for each_dict in tqdm(test_dataset):\n", " sentence = each_dict['headline'] # Get the sentence from the dictionary\n", " image_id = each_dict['image_id'] # Get the image_id from the dictionary\n", " if \"[MASK]\" in sentence: # See if it has a [MASK] in headline\n", " result = unmasker(sentence) # Unmask the sentence\n", "\n", " # Make a list of indices where [MASK] is present in the sentence\n", " # If there are more than one [MASK] in the sentence, then add them as separate entries in the result list\n", " indices = [i for i, x in enumerate(sentence.split()) if x == \"[MASK]\"]\n", " if len(indices) > 1:\n", " masked_word_idx_list = []\n", " for i, each_result in enumerate(result):\n", " # Get the top scoring word\n", " top_word = each_result[0]['token_str']\n", " all_masked_words.append([image_id, indices[i], top_word])\n", " else:\n", " all_masked_words.append([image_id, indices[0], result[0]['token_str']])\n", "\n", "final_masked_words = [l[0] for l in all_masked_words]" ], "metadata": { "collapsed": false } }, { "cell_type": "markdown", "source": [ "## Print first 5 rows of the masked words list" ], "metadata": { "collapsed": false } }, { "cell_type": "code", "execution_count": 13, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['00040f12-c19e-54db-9513-d4a3d9ce30f1', '0006d6e6-a16f-5d69-a307-0e7e1b659075', '000755c6-df96-502a-a3e4-8f78f0919a8c', '0038ee8b-3f57-5838-a201-509d4bcd1c06', '0048f974-e081-54ee-b0c4-e30b5f66c763']\n" ] } ], "source": [ "print(final_masked_words[:5])" ], "metadata": { "collapsed": false } }, { "cell_type": "markdown", "source": [ "## Save the results as a dataframe and print first 5 rows of the dataframe" ], "metadata": { "collapsed": false } }, { "cell_type": "code", "execution_count": 15, "outputs": [ { "data": { "text/plain": " id token_index token\n0 00040f12-c19e-54db-9513-d4a3d9ce30f1 11 .\n1 0006d6e6-a16f-5d69-a307-0e7e1b659075 5 the\n2 000755c6-df96-502a-a3e4-8f78f0919a8c 2 a\n3 0038ee8b-3f57-5838-a201-509d4bcd1c06 0 regular\n4 0048f974-e081-54ee-b0c4-e30b5f66c763 6 a", "text/html": "
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
idtoken_indextoken
000040f12-c19e-54db-9513-d4a3d9ce30f111.
10006d6e6-a16f-5d69-a307-0e7e1b6590755the
2000755c6-df96-502a-a3e4-8f78f0919a8c2a
30038ee8b-3f57-5838-a201-509d4bcd1c060regular
40048f974-e081-54ee-b0c4-e30b5f66c7636a
\n
" }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Save the results in a dataframe with column name id,token_index,token\n", "df = pd.DataFrame(all_masked_words, columns=['id', 'token_index', 'token'])\n", "df.head()" ], "metadata": { "collapsed": false } }, { "cell_type": "markdown", "source": [ "## Save the dataframe as a csv file" ], "metadata": { "collapsed": false } }, { "cell_type": "code", "execution_count": 16, "outputs": [], "source": [ "df.to_csv('sample_result.csv', index=False)" ], "metadata": { "collapsed": false } } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.6" } }, "nbformat": 4, "nbformat_minor": 0 }