{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# 1. Introduction and Context","metadata":{}},{"cell_type":"markdown","source":"Masked-Language Modeling using Transformer based methods will be used.\n\nFollowing inputs are to be included as a first step. (the inputs on train data, test data and submission sample files are anyways included upfront)\n\n* bigger-govt-dataset-list (for additional datasets)\n* coleridge-mlm-model (pre-trained model)\n* coleridge-packages (transformer packages)\n\nWe have been facing some issues with fsspec initially and hence the following are also added as inputs.\n* icevision-080 (to have fsspec utils related issues fixed)","metadata":{}},{"cell_type":"markdown","source":"# 2. Install Packages","metadata":{}},{"cell_type":"code","source":"# Install necessary packages\n!pip install datasets --no-index --find-links=file:///kaggle/input/coleridge-packages/packages/datasets\n!pip install ../input/coleridge-packages/seqeval-1.2.2-py3-none-any.whl\n!pip install ../input/coleridge-packages/tokenizers-0.10.1-cp37-cp37m-manylinux1_x86_64.whl\n!pip install ../input/coleridge-packages/transformers-4.5.0.dev0-py3-none-any.whl\n#!pip install ../input/fsspec/fsspec-0.9.0-py3-none-any.whl\n!pip install ../input/icevision-080/fsspec-2021.5.0-py3-none-any.whl\n\n# Clears output\nfrom IPython.display import clear_output\nclear_output()","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:46:33.842192Z","iopub.execute_input":"2021-06-21T10:46:33.842703Z","iopub.status.idle":"2021-06-21T10:48:35.529858Z","shell.execute_reply.started":"2021-06-21T10:46:33.842602Z","shell.execute_reply":"2021-06-21T10:48:35.52809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 3. Configuration Params","metadata":{}},{"cell_type":"code","source":"COMPUTE_CV = False\nALL_BLENDED = False\nBASELINE_HELPING = False\nMATCH_ONLY = False\nMLM_ONLY = False\nKEN_MATCHING = True\nBS_CLEANING = False\nTHEO_MERGE = False\nSEED = 124","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:49:20.344275Z","iopub.execute_input":"2021-06-21T10:49:20.344667Z","iopub.status.idle":"2021-06-21T10:49:20.350015Z","shell.execute_reply.started":"2021-06-21T10:49:20.344631Z","shell.execute_reply":"2021-06-21T10:49:20.348897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 4. Import Libraries","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport os\nimport re\nimport json\nimport time\nimport datetime\nimport random\nimport glob\nimport importlib\n\nfrom tqdm.autonotebook import tqdm\n\nimport torch\nfrom datasets import load_dataset\nfrom transformers import AutoTokenizer, DataCollatorForLanguageModeling, \\\nAutoModelForMaskedLM, Trainer, TrainingArguments, pipeline\n\nfrom typing import List\nimport string\nfrom functools import partial\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nsns.set()\nrandom.seed(SEED)\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\nsample_submission = pd.read_csv('../input/coleridgeinitiative-show-us-the-data/sample_submission.csv')\nif len(sample_submission) > 4: COMPUTE_CV = False\nif COMPUTE_CV: \n    print('The notebook will compute CV score but commit notebook will not')\nelse:\n    print('This submission notebook will only be used to submit result')","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:51:36.956653Z","iopub.execute_input":"2021-06-21T10:51:36.957033Z","iopub.status.idle":"2021-06-21T10:51:46.30594Z","shell.execute_reply.started":"2021-06-21T10:51:36.957Z","shell.execute_reply":"2021-06-21T10:51:46.305147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#!pip install --upgrade fsspec\n#!pip install fsspec==0.9.0","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:52:18.025607Z","iopub.execute_input":"2021-06-21T10:52:18.026215Z","iopub.status.idle":"2021-06-21T10:52:18.029643Z","shell.execute_reply.started":"2021-06-21T10:52:18.026166Z","shell.execute_reply":"2021-06-21T10:52:18.028938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 5. Load Dataset","metadata":{}},{"cell_type":"code","source":"train_path = '../input/coleridgeinitiative-show-us-the-data/train.csv'\ntrain_files_path = '../input/coleridgeinitiative-show-us-the-data/train'\ntrain = pd.read_csv(train_path)\n\nif COMPUTE_CV: \n    sample_submission = train\n    paper_test_folder = '../input/coleridgeinitiative-show-us-the-data/train'\n    test_files_path = paper_test_folder\nelse:\n    sample_submission = pd.read_csv('../input/coleridgeinitiative-show-us-the-data/sample_submission.csv')\n    paper_test_folder = '../input/coleridgeinitiative-show-us-the-data/test'\n    test_files_path = paper_test_folder\n    \nadnl_govt_labels_path = '../input/bigger-govt-dataset-list/data_set_800.csv'","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:52:20.668016Z","iopub.execute_input":"2021-06-21T10:52:20.668522Z","iopub.status.idle":"2021-06-21T10:52:20.822853Z","shell.execute_reply.started":"2021-06-21T10:52:20.668487Z","shell.execute_reply":"2021-06-21T10:52:20.821648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"publications = {}\nfor paper_id in tqdm(sample_submission['Id']):\n    with open(f'{paper_test_folder}/{paper_id}.json', 'r') as f:\n        paper = json.load(f)\n        publications[paper_id] = paper","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:52:39.352011Z","iopub.execute_input":"2021-06-21T10:52:39.352408Z","iopub.status.idle":"2021-06-21T10:52:39.426587Z","shell.execute_reply.started":"2021-06-21T10:52:39.352375Z","shell.execute_reply":"2021-06-21T10:52:39.42555Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 6. Literal Matching\n\n### We will create a knowledge bank.","metadata":{}},{"cell_type":"code","source":"all_labels = set()\n\nfor label_1, label_2, label_3 in train[['dataset_title', 'dataset_label', 'cleaned_label']].itertuples(index=False):\n    all_labels.add(str(label_1).lower())\n    all_labels.add(str(label_2).lower())\n    all_labels.add(str(label_3).lower())\n    \nprint(f'No. different labels: {len(all_labels)}')","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:53:22.314102Z","iopub.execute_input":"2021-06-21T10:53:22.314533Z","iopub.status.idle":"2021-06-21T10:53:22.378437Z","shell.execute_reply.started":"2021-06-21T10:53:22.314493Z","shell.execute_reply":"2021-06-21T10:53:22.377292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Let's use additional Govt datasets","metadata":{}},{"cell_type":"code","source":"adnl_govt_labels = pd.read_csv(adnl_govt_labels_path)\n\nfor l in adnl_govt_labels.title:\n    all_labels.add(l)\n    \nall_labels = set(all_labels)\nprint(f'No. different labels: {len(all_labels)}')","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:53:32.698218Z","iopub.execute_input":"2021-06-21T10:53:32.698656Z","iopub.status.idle":"2021-06-21T10:53:32.723383Z","shell.execute_reply.started":"2021-06-21T10:53:32.698621Z","shell.execute_reply":"2021-06-21T10:53:32.722119Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Now, let's match on test data","metadata":{}},{"cell_type":"code","source":"def clean_text(txt):\n    return re.sub('[^A-Za-z0-9]+', ' ', str(txt).lower()).strip()\n\n\ndef totally_clean_text(txt):\n    txt = clean_text(txt)\n    txt = re.sub(' +', ' ', txt)\n    return txt\n\nif not BS_CLEANING:\n    def text_cleaning(text):\n        '''\n        Converts all text to lower case, Removes special charecters, emojis and multiple spaces\n        text - Sentence that needs to be cleaned\n        '''\n        text = re.sub('[^A-Za-z0-9]+', ' ', str(text).lower()).strip()\n        text = re.sub(' +', ' ', text)\n        emoji_pattern = re.compile(\"[\"\n                                   u\"\\U0001F600-\\U0001F64F\"  # emoticons\n                                   u\"\\U0001F300-\\U0001F5FF\"  # symbols & pictographs\n                                   u\"\\U0001F680-\\U0001F6FF\"  # transport & map symbols\n                                   u\"\\U0001F1E0-\\U0001F1FF\"  # flags (iOS)\n                                   \"]+\", flags=re.UNICODE)\n        text = emoji_pattern.sub(r'', text)\n        return text\nelse:\n    def text_cleaning(text):\n        '''\n        Converts all text to lower case, Removes special charecters, emojis and multiple spaces\n        text - Sentence that needs to be cleaned\n        '''\n        text = ''.join([k for k in text if k not in string.punctuation])\n        text = re.sub('[^A-Za-z0-9]+', ' ', str(text).lower()).strip()\n        # text = re.sub(\"/'+/g\", ' ', text)\n        return text\n\n\ndef read_json_pub(filename, train_data_path=train_files_path, output='text'):\n    json_path = os.path.join(train_data_path, (filename+'.json'))\n    headings = []\n    contents = []\n    combined = []\n    with open(json_path, 'r') as f:\n        json_decode = json.load(f)\n        for data in json_decode:\n            headings.append(data.get('section_title'))\n            contents.append(data.get('text'))\n            combined.append(data.get('section_title'))\n            combined.append(data.get('text'))\n    \n    all_headings = ' '.join(headings)\n    all_contents = ' '.join(contents)\n    all_data = '. '.join(combined)\n    \n    if output == 'text':\n        return all_contents\n    elif output == 'head':\n        return all_headings\n    else:\n        return all_data","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:54:00.041926Z","iopub.execute_input":"2021-06-21T10:54:00.042339Z","iopub.status.idle":"2021-06-21T10:54:00.05806Z","shell.execute_reply.started":"2021-06-21T10:54:00.042306Z","shell.execute_reply":"2021-06-21T10:54:00.056638Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if not KEN_MATCHING and not MLM_ONLY:\n    literal_preds = []\n    for paper_id in tqdm(sample_submission['Id']):\n        paper = publications[paper_id]\n        text_1 = '. '.join(section['text'] for section in paper).lower()\n        text_2 = totally_clean_text(text_1)\n\n        labels = set()\n        for label in all_labels:\n            if label in text_1 or label in text_2:\n                labels.add(clean_text(label))\n\n        literal_preds.append('|'.join(labels))\n    literal_preds[:5]","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:55:01.776001Z","iopub.execute_input":"2021-06-21T10:55:01.776422Z","iopub.status.idle":"2021-06-21T10:55:01.783554Z","shell.execute_reply.started":"2021-06-21T10:55:01.776384Z","shell.execute_reply":"2021-06-21T10:55:01.782481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Ken Matching","metadata":{}},{"cell_type":"code","source":"literal_preds = []\n\nif KEN_MATCHING and not MLM_ONLY:\n    literal_preds = []\n    to_append = []\n    for index, row in tqdm(sample_submission.iterrows(), total=len(sample_submission)):\n        to_append = [row['Id'],'']\n        large_string = str(read_json_pub(row['Id'], test_files_path))\n        clean_string = text_cleaning(large_string)\n        for index, row2 in adnl_govt_labels.iterrows():\n            query_string = str(row2['title'])\n            if query_string in clean_string:\n                if to_append[1] != '' and clean_text(query_string) not in to_append[1]:\n                    to_append[1] = to_append[1] + '|' + clean_text(query_string)\n                if to_append[1] == '':\n                    to_append[1] = clean_text(query_string)\n        literal_preds.append(*to_append[1:])\n\nelif MLM_ONLY:\n    print('This notebook will only use MLM model to predict.')","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:56:22.036774Z","iopub.execute_input":"2021-06-21T10:56:22.037213Z","iopub.status.idle":"2021-06-21T10:56:23.331843Z","shell.execute_reply.started":"2021-06-21T10:56:22.037178Z","shell.execute_reply":"2021-06-21T10:56:23.330761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 7. Masked Dataset Modeling","metadata":{}},{"cell_type":"markdown","source":"### Let's set paths and hyperparams","metadata":{}},{"cell_type":"code","source":"if not MATCH_ONLY:\n    PRETRAINED_PATH = '../input/coleridge-mlm-model/output-mlm/checkpoint-36000'\n    TOKENIZER_PATH = '../input/coleridge-mlm-model/model_tokenizer'\n\n    MAX_LENGTH = 64\n    OVERLAP = 20\n\n    PREDICT_BATCH = 32 # a higher value requires higher GPU memory usage\n\n    DATASET_SYMBOL = '$' # this symbol represents a dataset name\n    NONDATA_SYMBOL = '#' # this symbol represents a non-dataset name","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:57:56.490463Z","iopub.execute_input":"2021-06-21T10:57:56.490949Z","iopub.status.idle":"2021-06-21T10:57:56.496283Z","shell.execute_reply.started":"2021-06-21T10:57:56.490907Z","shell.execute_reply":"2021-06-21T10:57:56.495136Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 8. Transform Data into MLM format","metadata":{}},{"cell_type":"markdown","source":"### Load Model and Tokenizer","metadata":{}},{"cell_type":"code","source":"if not MATCH_ONLY:\n    tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, use_fast=True)\n    model = AutoModelForMaskedLM.from_pretrained(PRETRAINED_PATH)\n\n    mlm = pipeline(\n        'fill-mask', \n        model=model,\n        tokenizer=tokenizer,\n        device=0 if torch.cuda.is_available() else -1\n    )","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:58:33.095255Z","iopub.execute_input":"2021-06-21T10:58:33.095601Z","iopub.status.idle":"2021-06-21T10:58:44.385223Z","shell.execute_reply.started":"2021-06-21T10:58:33.095572Z","shell.execute_reply":"2021-06-21T10:58:44.384082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Auxiliary Functions","metadata":{}},{"cell_type":"code","source":"def jaccard_similarity(s1, s2):\n    l1 = s1.split(\" \")\n    l2 = s2.split(\" \")    \n    intersection = len(list(set(l1).intersection(l2)))\n    union = (len(l1) + len(l2)) - intersection\n    return float(intersection) / union\n\ndef clean_paper_sentence(s):\n    \"\"\"\n    This function is essentially clean_text without lowercasing.\n    \"\"\"\n    s = re.sub('[^A-Za-z0-9]+', ' ', str(s)).strip()\n    s = re.sub(' +', ' ', s)\n    return s\n\ndef shorten_sentences(sentences):\n    \"\"\"\n    Sentences that have more than MAX_LENGTH words will be split\n    into multiple sentences with overlappings.\n    \"\"\"\n    short_sentences = []\n    for sentence in sentences:\n        words = sentence.split()\n        if len(words) > MAX_LENGTH:\n            for p in range(0, len(words), MAX_LENGTH - OVERLAP):\n                short_sentences.append(' '.join(words[p:p+MAX_LENGTH]))\n        else:\n            short_sentences.append(sentence)\n    return short_sentences\n\nconnection_tokens = {'s', 'of', 'and', 'in', 'on', 'for', 'data', 'dataset'}\ndef find_mask_candidates(sentence):\n    \"\"\"\n    Extract masking candidates for Masked Dataset Modeling from a given $sentence.\n    A candidate should be a continuous sequence of at least 2 words, \n    each of these words either has the first letter in uppercase or is one of\n    the connection words ($connection_tokens). Furthermore, the connection \n    tokens are not allowed to appear at the beginning and the end of the\n    sequence.\n    \"\"\"\n    def candidate_qualified(words):\n        while len(words) and words[0].lower() in connection_tokens:\n            words = words[1:]\n        while len(words) and words[-1].lower() in connection_tokens:\n            words = words[:-1]\n        \n        return len(words) >= 2\n    \n    candidates = []\n    \n    phrase_start, phrase_end = -1, -1\n    for id in range(1, len(sentence)):\n        word = sentence[id]\n        if word[0].isupper() or word in connection_tokens:\n            if phrase_start == -1:\n                phrase_start = phrase_end = id\n            else:\n                phrase_end = id\n        else:\n            if phrase_start != -1:\n                if candidate_qualified(sentence[phrase_start:phrase_end+1]):\n                    candidates.append((phrase_start, phrase_end))\n                phrase_start = phrase_end = -1\n    \n    if phrase_start != -1:\n        if candidate_qualified(sentence[phrase_start:phrase_end+1]):\n            candidates.append((phrase_start, phrase_end))\n    \n    return candidates","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:58:55.247823Z","iopub.execute_input":"2021-06-21T10:58:55.248284Z","iopub.status.idle":"2021-06-21T10:58:55.266994Z","shell.execute_reply.started":"2021-06-21T10:58:55.248246Z","shell.execute_reply":"2021-06-21T10:58:55.265561Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Transform","metadata":{}},{"cell_type":"code","source":"if not MATCH_ONLY:\n    mask = mlm.tokenizer.mask_token\n    all_test_data = []\n    \n    for paper_id in tqdm(sample_submission['Id']):\n        # load paper\n        paper = publications[paper_id]\n\n        # extract sentences\n        sentences = set([clean_paper_sentence(sentence) for section in paper \n                         for sentence in section['text'].split('.')\n                        ])\n        sentences = shorten_sentences(sentences) # make sentences short\n        sentences = [sentence for sentence in sentences if len(sentence) > 10] # only accept sentences with length > 10 chars\n        sentences = [sentence for sentence in sentences if any(word in sentence.lower() for word in ['data', 'study'])]\n        sentences = [sentence.split() for sentence in sentences] # sentence = list of words\n\n        # mask\n        test_data = []\n        for sentence in sentences:\n            for phrase_start, phrase_end in find_mask_candidates(sentence):\n                dt_point = sentence[:phrase_start] + [mask] + sentence[phrase_end+1:]\n                test_data.append((' '.join(dt_point), ' '.join(sentence[phrase_start:phrase_end+1]))) # (masked text, phrase)\n\n        all_test_data.append(test_data)","metadata":{"execution":{"iopub.status.busy":"2021-06-21T10:59:24.236937Z","iopub.execute_input":"2021-06-21T10:59:24.237307Z","iopub.status.idle":"2021-06-21T10:59:24.356001Z","shell.execute_reply.started":"2021-06-21T10:59:24.237267Z","shell.execute_reply":"2021-06-21T10:59:24.354673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 9. Prediction","metadata":{}},{"cell_type":"code","source":"if not MATCH_ONLY:\n    pred_mlm_labels = []\n\n    for test_data in tqdm(all_test_data):\n        pred_bag = set()\n\n        if len(test_data):\n            texts, phrases = list(zip(*test_data))\n            mlm_pred = []\n            for p_id in range(0, len(texts), PREDICT_BATCH):\n                batch_texts = texts[p_id:p_id+PREDICT_BATCH]\n                batch_pred = mlm(list(batch_texts), targets=[f' {DATASET_SYMBOL}', f' {NONDATA_SYMBOL}'])\n\n                if len(batch_texts) == 1:\n                    batch_pred = [batch_pred]\n\n                mlm_pred.extend(batch_pred)\n\n            for (result1, result2), phrase in zip(mlm_pred, phrases):\n                if (result1['score'] > result2['score']*2 and result1['token_str'] == DATASET_SYMBOL) or\\\n                   (result2['score'] > result1['score']*2 and result2['token_str'] == NONDATA_SYMBOL):\n                    pred_bag.add(clean_text(phrase))\n\n        # filter labels by jaccard score \n        filtered_labels = []\n\n        for label in sorted(pred_bag, key=len, reverse=True):\n            if len(filtered_labels) == 0 or all(jaccard_similarity(label, got_label) < 0.75 for got_label in filtered_labels):\n                filtered_labels.append(label)\n\n        pred_mlm_labels.append('|'.join(filtered_labels))\n    \n    pred_mlm_labels[:5]","metadata":{"execution":{"iopub.status.busy":"2021-06-21T11:00:02.725768Z","iopub.execute_input":"2021-06-21T11:00:02.726202Z","iopub.status.idle":"2021-06-21T11:00:36.199167Z","shell.execute_reply.started":"2021-06-21T11:00:02.726166Z","shell.execute_reply":"2021-06-21T11:00:36.197841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 10. Baseline Model","metadata":{}},{"cell_type":"code","source":"def read_append_return(filename, train_files_path=train_files_path, output='text'):\n    \"\"\"\n    Function to read json file and then return the text data from them and append to the dataframe\n    \"\"\"\n    json_path = os.path.join(train_files_path, (filename+'.json'))\n    headings = []\n    contents = []\n    combined = []\n    with open(json_path, 'r') as f:\n        json_decode = json.load(f)\n        for data in json_decode:\n            headings.append(data.get('section_title'))\n            contents.append(data.get('text'))\n            combined.append(data.get('section_title'))\n            combined.append(data.get('text'))\n    \n    all_headings = ' '.join(headings)\n    all_contents = ' '.join(contents)\n    all_data = '. '.join(combined)\n    \n    if output == 'text':\n        return all_contents\n    elif output == 'head':\n        return all_headings\n    else:\n        return all_data\n    \n    \ndef text_cleaning(text):\n    '''\n    Converts all text to lower case, Removes special charecters, emojis and multiple spaces\n    text - Sentence that needs to be cleaned\n    '''\n    text = ''.join([k for k in text if k not in string.punctuation])\n    text = re.sub('[^A-Za-z0-9]+', ' ', str(text).lower()).strip()\n    # text = re.sub(\"/'+/g\", ' ', text)\n    return text","metadata":{"execution":{"iopub.status.busy":"2021-06-21T11:00:50.575315Z","iopub.execute_input":"2021-06-21T11:00:50.575671Z","iopub.status.idle":"2021-06-21T11:00:50.58661Z","shell.execute_reply.started":"2021-06-21T11:00:50.57564Z","shell.execute_reply":"2021-06-21T11:00:50.585121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if BASELINE_HELPING or ALL_BLENDED:\n    tqdm.pandas()\n\n    train['text'] = train['Id'].progress_apply(read_append_return)\n\n    if not COMPUTE_CV:\n        sample_submission['text'] = sample_submission['Id'].progress_apply(partial(read_append_return, train_files_path=test_files_path))\n\n    train.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-21T11:01:02.949344Z","iopub.execute_input":"2021-06-21T11:01:02.949724Z","iopub.status.idle":"2021-06-21T11:01:02.955842Z","shell.execute_reply.started":"2021-06-21T11:01:02.949689Z","shell.execute_reply":"2021-06-21T11:01:02.954552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if BASELINE_HELPING or ALL_BLENDED:\n    tqdm.pandas()\n    \n    train['text'] = train['text'].progress_apply(text_cleaning)","metadata":{"execution":{"iopub.status.busy":"2021-06-21T11:01:09.153534Z","iopub.execute_input":"2021-06-21T11:01:09.153942Z","iopub.status.idle":"2021-06-21T11:01:09.158564Z","shell.execute_reply.started":"2021-06-21T11:01:09.153905Z","shell.execute_reply":"2021-06-21T11:01:09.157468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if BASELINE_HELPING or ALL_BLENDED:\n    temp_1 = [x.lower() for x in train['dataset_label'].unique()]\n    temp_2 = [x.lower() for x in train['dataset_title'].unique()]\n    temp_3 = [x.lower() for x in train['cleaned_label'].unique()]\n\n    existing_labels = set(temp_1 + temp_2 + temp_3)\n\n    print(f'len(temp_1) = {len(temp_1)}')\n    print(f'len(temp_2) = {len(temp_2)}')\n    print(f'len(temp_3) = {len(temp_3)}')\n    print(f'len(existing_labels) = {len(existing_labels)}')\n\n    id_list = []\n    lables_list = []\n    for index, row in tqdm(sample_submission.iterrows()):\n        sample_text = row['text']\n        row_id = row['Id']\n        temp_df = train[train['text'] == text_cleaning(sample_text)]\n        cleaned_labels = temp_df['cleaned_label'].to_list()\n\n        for known_label in existing_labels:\n            if known_label in sample_text.lower():\n                cleaned_labels.append(clean_text(known_label))\n\n        cleaned_labels = [clean_text(x) for x in cleaned_labels]\n        cleaned_labels = set(cleaned_labels)\n        lables_list.append('|'.join(cleaned_labels))\n        id_list.append(row_id)","metadata":{"execution":{"iopub.status.busy":"2021-06-21T11:01:32.780225Z","iopub.execute_input":"2021-06-21T11:01:32.780737Z","iopub.status.idle":"2021-06-21T11:01:32.792149Z","shell.execute_reply.started":"2021-06-21T11:01:32.780694Z","shell.execute_reply":"2021-06-21T11:01:32.790936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 11. Aggregate Final Predictions & Write into CSV format","metadata":{}},{"cell_type":"code","source":"pred_mlm_labels","metadata":{"execution":{"iopub.status.busy":"2021-06-21T11:02:14.10605Z","iopub.execute_input":"2021-06-21T11:02:14.106542Z","iopub.status.idle":"2021-06-21T11:02:14.117728Z","shell.execute_reply.started":"2021-06-21T11:02:14.10649Z","shell.execute_reply":"2021-06-21T11:02:14.116283Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_predictions = []\n\nif ALL_BLENDED:\n    for literal_match, mlm_pred, lables_match in zip(literal_preds, pred_mlm_labels, lables_list):\n        temp = [literal_match, mlm_pred, lables_match]\n        temp = [pred for pred in temp if pred]\n        temp = ('|').join(temp)\n        final_predictions.append(temp)\n        \nelif BASELINE_HELPING:\n    for literal_match, mlm_pred, lables_match in zip(literal_preds, pred_mlm_labels, lables_list):\n        if literal_match:\n            final_predictions.append(literal_match)\n        elif lables_match:\n            final_predictions.append(lables_match)\n        else:\n            final_predictions.append(mlm_pred)\n\nelif MATCH_ONLY:\n    final_predictions = literal_preds\n\nelif MLM_ONLY:\n    final_predictions = pred_mlm_labels\n\nelif THEO_MERGE:\n    for i in range(len(literal_preds)):\n        pred_naive = literal_preds[i].split('|')\n        pred_model = pred_mlm_labels[i].split('|')\n        pred_model_kept = []\n        for pred_m in pred_model:\n            kept = True\n            for pred_n in pred_naive:\n                if pred_m in pred_n or pred_n in pred_m:\n                    kept = False\n            if kept:\n                pred_model_kept.append(pred_m)\n        final_predictions.append(\"|\".join(pred_naive + pred_model_kept))\n    \nelse:    \n    for literal_match, mlm_pred in zip(literal_preds, pred_mlm_labels):\n        if literal_match:\n            final_predictions.append(literal_match)\n        else:\n            final_predictions.append(mlm_pred)\n\nsample_submission['PredictionString'] = final_predictions","metadata":{"execution":{"iopub.status.busy":"2021-06-21T11:04:01.816769Z","iopub.execute_input":"2021-06-21T11:04:01.817156Z","iopub.status.idle":"2021-06-21T11:04:01.831417Z","shell.execute_reply.started":"2021-06-21T11:04:01.817121Z","shell.execute_reply":"2021-06-21T11:04:01.830155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission['PredictionString'] = final_predictions\nsample_submission[['Id', 'PredictionString']].to_csv('submission.csv', index=False)\n\nsample_submission.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-21T11:04:12.036436Z","iopub.execute_input":"2021-06-21T11:04:12.036819Z","iopub.status.idle":"2021-06-21T11:04:12.058714Z","shell.execute_reply.started":"2021-06-21T11:04:12.036787Z","shell.execute_reply":"2021-06-21T11:04:12.05747Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission.shape","metadata":{"execution":{"iopub.status.busy":"2021-06-21T11:04:26.014271Z","iopub.execute_input":"2021-06-21T11:04:26.014624Z","iopub.status.idle":"2021-06-21T11:04:26.021131Z","shell.execute_reply.started":"2021-06-21T11:04:26.014594Z","shell.execute_reply":"2021-06-21T11:04:26.019981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 12. Evaluation","metadata":{}},{"cell_type":"code","source":"# Reference from - https://www.kaggle.com/c/coleridgeinitiative-show-us-the-data/discussion/230091\n\ndef compute_fbeta(y_true: List[List[str]],\n                  y_pred: List[List[str]],\n                  beta: float = 0.5) -> float:\n    \"\"\"Compute the Jaccard-based micro FBeta score.\n\n    References\n    ----------\n    - https://www.kaggle.com/c/coleridgeinitiative-show-us-the-data/overview/evaluation\n    \"\"\"\n\n    def _jaccard_similarity(str1: str, str2: str) -> float:\n        a = set(str1.split()) \n        b = set(str2.split())\n        c = a.intersection(b)\n        return float(len(c)) / (len(a) + len(b) - len(c))\n\n    tp = 0  # true positive\n    fp = 0  # false positive\n    fn = 0  # false negative\n    for ground_truth_list, predicted_string_list in zip(y_true, y_pred):\n        predicted_string_list_sorted = sorted(predicted_string_list)\n        for ground_truth in sorted(ground_truth_list):            \n            if len(predicted_string_list_sorted) == 0:\n                fn += 1\n            else:\n                similarity_scores = [\n                    _jaccard_similarity(ground_truth, predicted_string)\n                    for predicted_string in predicted_string_list_sorted\n                ]\n                matched_idx = np.argmax(similarity_scores)\n                if similarity_scores[matched_idx] >= 0.5:\n                    predicted_string_list_sorted.pop(matched_idx)\n                    tp += 1\n                else:\n                    fn += 1\n        fp += len(predicted_string_list_sorted)\n\n    tp *= (1 + beta ** 2)\n    fn *= beta ** 2\n    fbeta_score = tp / (tp + fp + fn)\n    return fbeta_score","metadata":{"execution":{"iopub.status.busy":"2021-06-21T11:04:39.606159Z","iopub.execute_input":"2021-06-21T11:04:39.606542Z","iopub.status.idle":"2021-06-21T11:04:39.617311Z","shell.execute_reply.started":"2021-06-21T11:04:39.606508Z","shell.execute_reply":"2021-06-21T11:04:39.616429Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if COMPUTE_CV:\n    COMPUTE_CV_SCORE = compute_fbeta(sample_submission['cleaned_label'].apply(lambda x: [x]),\\\n                  sample_submission['PredictionString'].apply(lambda x: x.split('|')))\n    print('COMPUTE_CV_SCORE =', COMPUTE_CV_SCORE)\nelse:\n    print(f'COMPUTE_CV = {COMPUTE_CV}')\n    \nprint(f'ALL_BLENDED = {ALL_BLENDED}')\nprint(f'BASELINE_HELPING = {BASELINE_HELPING}')\nprint(f'MATCH_ONLY = {MATCH_ONLY}')\nprint(f'MLM_ONLY = {MLM_ONLY}')\nprint(f'KEN_MATCHING = {KEN_MATCHING}')\nprint(f'BS_CLEANING = {BS_CLEANING}')\nprint(f'THEO_MERGE = {THEO_MERGE}')\nprint(f'SEED = {SEED}')","metadata":{"execution":{"iopub.status.busy":"2021-06-21T11:05:48.200938Z","iopub.execute_input":"2021-06-21T11:05:48.201334Z","iopub.status.idle":"2021-06-21T11:05:48.211664Z","shell.execute_reply.started":"2021-06-21T11:05:48.201302Z","shell.execute_reply":"2021-06-21T11:05:48.210679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}