{"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":"# MLiP 30: Coleridge Initiave using Pattern Matching and SciBERT\n\nThis notebook is created for the challeng \"Coleridge Inititive - Show US the Data\" and is part of the course NWI-IMC030 Machine Learning in Practice. We used the notebook [Coleridge: Matching + BERT NER](https://www.kaggle.com/tungmphung/coleridge-matching-bert-ner) by Tung M Phung as our baseline. Therefore, most of the notebook is similar to that notebook. The changes we made compared to the baseline notebook are:\n1. Using SciBERT as the pretrained model instead of BERT.\n2. Implementation of pattern matching (`characteristic_pattern_match()`) and use it to extract relevant sentences.\n","metadata":{}},{"cell_type":"code","source":"This notebook gives a simple combination of literal matching, pattern matching and Named Entity Recognition using SciBERT.\n\nThe training phase of the SciBERT model was done in another kernel.","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"MAX_SAMPLE = None # set a small number for experimentation, set None for production.","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:32:34.603069Z","iopub.execute_input":"2021-06-13T07:32:34.603464Z","iopub.status.idle":"2021-06-13T07:32:34.609134Z","shell.execute_reply.started":"2021-06-13T07:32:34.603361Z","shell.execute_reply":"2021-06-13T07:32:34.608268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Install packages","metadata":{}},{"cell_type":"code","source":"!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","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:32:34.614232Z","iopub.execute_input":"2021-06-13T07:32:34.614885Z","iopub.status.idle":"2021-06-13T07:34:01.590692Z","shell.execute_reply.started":"2021-06-13T07:32:34.614844Z","shell.execute_reply":"2021-06-13T07:34:01.589623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Import","metadata":{}},{"cell_type":"code","source":"import os\nimport re\nimport json\nimport time\nimport datetime\nimport random\nimport glob\nimport importlib\n\nimport numpy as np\nimport pandas as pd\n\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nrandom.seed(123)\nnp.random.seed(456)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-06-13T07:34:01.594932Z","iopub.execute_input":"2021-06-13T07:34:01.595211Z","iopub.status.idle":"2021-06-13T07:34:02.340018Z","shell.execute_reply.started":"2021-06-13T07:34:01.595179Z","shell.execute_reply":"2021-06-13T07:34:02.339185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load data","metadata":{}},{"cell_type":"code","source":"train_path = '../input/coleridgeinitiative-show-us-the-data/train.csv'\ntrain = pd.read_csv(train_path)\ntrain = train[:MAX_SAMPLE]\n\npaper_train_folder = '../input/coleridgeinitiative-show-us-the-data/train'\npapers = {}\nfor paper_id in train['Id'].unique():\n    with open(f'{paper_train_folder}/{paper_id}.json', 'r') as f:\n        paper = json.load(f)\n        papers[paper_id] = paper","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:02.341518Z","iopub.execute_input":"2021-06-13T07:34:02.341897Z","iopub.status.idle":"2021-06-13T07:34:56.663023Z","shell.execute_reply.started":"2021-06-13T07:34:02.341859Z","shell.execute_reply":"2021-06-13T07:34:56.662227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission_path = '../input/coleridgeinitiative-show-us-the-data/sample_submission.csv'\nsample_submission = pd.read_csv(sample_submission_path)\n\npaper_test_folder = '../input/coleridgeinitiative-show-us-the-data/test'\nfor paper_id in sample_submission['Id']:\n    with open(f'{paper_test_folder}/{paper_id}.json', 'r') as f:\n        paper = json.load(f)\n        papers[paper_id] = paper","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:56.665565Z","iopub.execute_input":"2021-06-13T07:34:56.665914Z","iopub.status.idle":"2021-06-13T07:34:56.699306Z","shell.execute_reply.started":"2021-06-13T07:34:56.665877Z","shell.execute_reply":"2021-06-13T07:34:56.698659Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Literal matching","metadata":{}},{"cell_type":"markdown","source":"### Create a knowledge bank","metadata":{}},{"cell_type":"code","source":"# Create a knowledge bank from all labels present in the data\nall_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-13T07:34:56.702662Z","iopub.execute_input":"2021-06-13T07:34:56.702913Z","iopub.status.idle":"2021-06-13T07:34:56.757593Z","shell.execute_reply.started":"2021-06-13T07:34:56.702888Z","shell.execute_reply":"2021-06-13T07:34:56.756822Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Matching on test data","metadata":{}},{"cell_type":"code","source":"# Clean out characters other than text\ndef clean_text(txt):\n    return re.sub('[^A-Za-z0-9]+', ' ', str(txt).lower()).strip()\n\ndef totally_clean_text(txt):\n    txt = clean_text(txt)\n    txt = re.sub(' +', ' ', txt)\n    return txt","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:56.760167Z","iopub.execute_input":"2021-06-13T07:34:56.760512Z","iopub.status.idle":"2021-06-13T07:34:56.766251Z","shell.execute_reply.started":"2021-06-13T07:34:56.760478Z","shell.execute_reply":"2021-06-13T07:34:56.765372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Literal matching\nliteral_preds = []\n\nfor paper_id in sample_submission['Id']:\n    paper = papers[paper_id]\n    text_1 = '. '.join(section['text'] for section in paper).lower()\n    text_2 = totally_clean_text(text_1)\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))","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:56.767706Z","iopub.execute_input":"2021-06-13T07:34:56.7683Z","iopub.status.idle":"2021-06-13T07:34:56.880851Z","shell.execute_reply.started":"2021-06-13T07:34:56.768239Z","shell.execute_reply":"2021-06-13T07:34:56.880192Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"literal_preds[:5]","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:56.88204Z","iopub.execute_input":"2021-06-13T07:34:56.882347Z","iopub.status.idle":"2021-06-13T07:34:56.890462Z","shell.execute_reply.started":"2021-06-13T07:34:56.882314Z","shell.execute_reply":"2021-06-13T07:34:56.889523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Bert prediction","metadata":{"trusted":true}},{"cell_type":"markdown","source":"### Paths and Hyperparameters","metadata":{}},{"cell_type":"code","source":"MAX_LENGTH = 64 # max no. words for each sentence.\nOVERLAP = 20 # if a sentence exceeds MAX_LENGTH, we split it to multiple sentences with overlapping\n\nPREDICT_BATCH = 64000 \n# Use coleridge-scibert-models instead of coleridge-bert-models in the paths\nPRETRAINED_PATH = '../input/coleridge-scibert-models/output/checkpoint-60000'\nTEST_INPUT_SAVE_PATH = './input_data'\nTEST_NER_DATA_FILE = 'test_ner_input.json'\nTRAIN_PATH = '../input/coleridge-scibert-models/train_ner.json'\nVAL_PATH = '../input/coleridge-scibert-models/train_ner.json'\n\nPREDICTION_SAVE_PATH = './pred'\nPREDICTION_FILE = 'test_predictions.txt'","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:56.891747Z","iopub.execute_input":"2021-06-13T07:34:56.892312Z","iopub.status.idle":"2021-06-13T07:34:56.899547Z","shell.execute_reply.started":"2021-06-13T07:34:56.892276Z","shell.execute_reply":"2021-06-13T07:34:56.898812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Transform data to NER format","metadata":{}},{"cell_type":"markdown","source":"Group by publication, training labels should have the same form as expected output.","metadata":{}},{"cell_type":"code","source":"train = train.groupby('Id').agg({\n    'pub_title': 'first',\n    'dataset_title': '|'.join,\n    'dataset_label': '|'.join,\n    'cleaned_label': '|'.join\n}).reset_index()\n\nprint(f'No. grouped training rows: {len(train)}')","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:56.901348Z","iopub.execute_input":"2021-06-13T07:34:56.901946Z","iopub.status.idle":"2021-06-13T07:34:57.262439Z","shell.execute_reply.started":"2021-06-13T07:34:56.901907Z","shell.execute_reply":"2021-06-13T07:34:57.261513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clean function without lowercasing and a function for shortening sentences to a specified MAX_LENGTH\ndef clean_training_text(txt):\n    \"\"\"\n    similar to the default clean_text function but without lowercasing.\n    \"\"\"\n    return re.sub('[^A-Za-z0-9]+', ' ', str(txt)).strip()\n\ndef shorten_sentences(sentences):\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","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:57.263755Z","iopub.execute_input":"2021-06-13T07:34:57.264243Z","iopub.status.idle":"2021-06-13T07:34:57.27133Z","shell.execute_reply.started":"2021-06-13T07:34:57.264204Z","shell.execute_reply":"2021-06-13T07:34:57.27049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Pattern matching without sentence cutting\n# For sentence cutting uncomment the intersect function and switch the return to intersect(sw,scl,tc, sentence)\n\ndef characteristic_pattern_match(sentence):\n    sentence = sentence.replace('-',' ')\n    sw = re.findall(r\"(dataset|database|data|study|model|survey)\", sentence.lower()) #keywords \n    scl = re.findall(r\"(([A-Z][a-z]+\\s((in|and|of|by|in|the|a)\\s)*)+[A-Z][a-z]+)\", sentence) #sequence of words starting with a capital letter connected by connection words\n    tc = re.findall(r\"(\\w*[A-Z]\\w*[A-Z]\\w*)\", sentence) #at least two caps in one word\n#     return intersect(sw,scl,tc, sentence)\n    return sw or scl or tc\n\n# def intersect(sw,scl,tc, sentence):\n#     comb = \"\"\n#     if sw:\n#         for s in sw:\n#             comb = comb + ' '+ s\n#     if scl:\n#         for sc in scl:\n#             comb = comb + ' '+ sc[0]\n#     if tc:\n#         for t in tc:\n#             comb = comb + ' '+ t\n#     out = [word for word in sentence.split(' ') if word in comb]\n#     output = ''\n#     for o in out:\n#         output += o+' '\n#     return output","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:57.272698Z","iopub.execute_input":"2021-06-13T07:34:57.273087Z","iopub.status.idle":"2021-06-13T07:34:57.285707Z","shell.execute_reply.started":"2021-06-13T07:34:57.273047Z","shell.execute_reply":"2021-06-13T07:34:57.284937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_rows = [] # test data in NER format\npaper_length = [] # store the number of sentences each paper has\n\nfor paper_id in sample_submission['Id']:\n    # load paper\n    paper = papers[paper_id]\n    \n    # extract sentences\n    sentences = [clean_training_text(sentence) for section in paper \n                 for sentence in section['text'].split('.')\n                ]\n    sentences = shorten_sentences(sentences) # make sentences short\n    # Without sentence cutting:\n    sentences = [sentence for sentence in sentences if characteristic_pattern_match(sentence)]\n    # With sentence cutting:\n#     sentences = [characteristic_pattern_match(sentence) for sentence in sentences if characteristic_pattern_match(sentence) != '']\n        \n    # collect all sentences in json\n    for sentence in sentences:\n        sentence_words = sentence.split()\n        dummy_tags = ['O']*len(sentence_words)\n        test_rows.append({'tokens' : sentence_words, 'tags' : dummy_tags})\n    \n    # track which sentence belongs to which data point\n    paper_length.append(len(sentences))\n    \nprint(f'total number of sentences: {len(test_rows)}')","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:57.286882Z","iopub.execute_input":"2021-06-13T07:34:57.28723Z","iopub.status.idle":"2021-06-13T07:34:57.448952Z","shell.execute_reply.started":"2021-06-13T07:34:57.287194Z","shell.execute_reply":"2021-06-13T07:34:57.448093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Do predict and collect results","metadata":{}},{"cell_type":"code","source":"os.environ[\"MODEL_PATH\"] = f\"{PRETRAINED_PATH}\"\nos.environ[\"TRAIN_FILE\"] = f\"{TRAIN_PATH}\"\nos.environ[\"VALIDATION_FILE\"] = f\"{VAL_PATH}\"\nos.environ[\"TEST_FILE\"] = f\"{TEST_INPUT_SAVE_PATH}/{TEST_NER_DATA_FILE}\"\nos.environ[\"OUTPUT_DIR\"] = f\"{PREDICTION_SAVE_PATH}\"","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:57.450372Z","iopub.execute_input":"2021-06-13T07:34:57.450761Z","iopub.status.idle":"2021-06-13T07:34:57.455991Z","shell.execute_reply.started":"2021-06-13T07:34:57.450714Z","shell.execute_reply":"2021-06-13T07:34:57.454883Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# copy my_seqeval.py to the working directory because the input directory is non-writable\n!cp /kaggle/input/coleridge-packages/my_seqeval.py ./\n\n# make necessart directories and files\nos.makedirs(TEST_INPUT_SAVE_PATH, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:57.457388Z","iopub.execute_input":"2021-06-13T07:34:57.458005Z","iopub.status.idle":"2021-06-13T07:34:58.124212Z","shell.execute_reply.started":"2021-06-13T07:34:57.457967Z","shell.execute_reply":"2021-06-13T07:34:58.122082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def bert_predict():\n    !python ../input/kaggle-ner-utils/kaggle_run_ner.py \\\n    --model_name_or_path \"$MODEL_PATH\" \\\n    --train_file \"$TRAIN_FILE\" \\\n    --validation_file \"$VALIDATION_FILE\" \\\n    --test_file \"$TEST_FILE\" \\\n    --output_dir \"$OUTPUT_DIR\" \\\n    --report_to 'none' \\\n    --seed 123 \\\n    --do_predict","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:58.132316Z","iopub.execute_input":"2021-06-13T07:34:58.132614Z","iopub.status.idle":"2021-06-13T07:34:58.139672Z","shell.execute_reply.started":"2021-06-13T07:34:58.132587Z","shell.execute_reply":"2021-06-13T07:34:58.138872Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"bert_outputs = []\n\nfor batch_begin in range(0, len(test_rows), PREDICT_BATCH):\n    # write data rows to input file\n    with open(f'{TEST_INPUT_SAVE_PATH}/{TEST_NER_DATA_FILE}', 'w') as f:\n        for row in test_rows[batch_begin:batch_begin+PREDICT_BATCH]:\n            json.dump(row, f)\n            f.write('\\n')\n    \n    # remove output dir\n    !rm -r \"$OUTPUT_DIR\"\n    \n    # do predict\n    bert_predict()\n    \n    # read predictions\n    with open(f'{PREDICTION_SAVE_PATH}/{PREDICTION_FILE}') as f:\n        this_preds = f.read().split('\\n')[:-1]\n        bert_outputs += [pred.split() for pred in this_preds]","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:34:58.142717Z","iopub.execute_input":"2021-06-13T07:34:58.14296Z","iopub.status.idle":"2021-06-13T07:35:28.466359Z","shell.execute_reply.started":"2021-06-13T07:34:58.142935Z","shell.execute_reply":"2021-06-13T07:35:28.463746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Restore Dataset labels from predictions","metadata":{}},{"cell_type":"code","source":"# get test sentences\ntest_sentences = [row['tokens'] for row in test_rows]\n\ndel test_rows","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:35:28.469346Z","iopub.status.idle":"2021-06-13T07:35:28.471818Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"bert_dataset_labels = [] # store all dataset labels for each publication\n\nfor length in paper_length:\n    labels = set()\n    for sentence, pred in zip(test_sentences[:length], bert_outputs[:length]):\n        curr_phrase = ''\n        for word, tag in zip(sentence, pred):\n            if tag == 'B': # start a new phrase\n                if curr_phrase:\n                    labels.add(curr_phrase)\n                    curr_phrase = ''\n                curr_phrase = word\n            elif tag == 'I' and curr_phrase: # continue the phrase\n                curr_phrase += ' ' + word\n            else: # end last phrase (if any)\n                if curr_phrase:\n                    labels.add(curr_phrase)\n                    curr_phrase = ''\n        # check if the label is the suffix of the sentence\n        if curr_phrase:\n            labels.add(curr_phrase)\n            curr_phrase = ''\n    \n    # record dataset labels for this publication\n    bert_dataset_labels.append(labels)\n    \n    del test_sentences[:length], bert_outputs[:length]","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:35:28.475548Z","iopub.status.idle":"2021-06-13T07:35:28.477931Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"bert_dataset_labels[:5]","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:35:28.481714Z","iopub.status.idle":"2021-06-13T07:35:28.4833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Filter based on Jaccard score and clean","metadata":{}},{"cell_type":"code","source":"# Calculate the difference between true labels and SciBERT predicted labels\ndef 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\nfiltered_bert_labels = []\n\nfor labels in bert_dataset_labels:\n    filtered = []\n    \n    for label in sorted(labels, key=len):\n        label = clean_text(label)\n        if len(filtered) == 0 or all(jaccard_similarity(label, got_label) < 0.75 for got_label in filtered):\n            filtered.append(label)\n    \n    filtered_bert_labels.append('|'.join(filtered))","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:35:28.485934Z","iopub.status.idle":"2021-06-13T07:35:28.487816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filtered_bert_labels[:5]","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:35:28.490463Z","iopub.status.idle":"2021-06-13T07:35:28.491199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Aggregate final predictions and write submission file","metadata":{}},{"cell_type":"code","source":"final_predictions = []\nfor literal_match, bert_pred in zip(literal_preds, filtered_bert_labels):\n    if literal_match:\n        final_predictions.append(literal_match)\n    else:\n        final_predictions.append(bert_pred)","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:35:28.493327Z","iopub.status.idle":"2021-06-13T07:35:28.494956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission['PredictionString'] = final_predictions\nsample_submission.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:35:28.4977Z","iopub.status.idle":"2021-06-13T07:35:28.499627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission.to_csv(f'submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2021-06-13T07:35:28.500815Z","iopub.status.idle":"2021-06-13T07:35:28.50444Z"},"trusted":true},"execution_count":null,"outputs":[]}]}