{"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":"This notebook shows how to fine-tune a BERT model (from huggingface) for our dataset recognition task.\n\nNote that internet is needed during the training phase (for downloading the bert-base-cased model). Internet can be turned off during prediction.","metadata":{}},{"cell_type":"markdown","source":"## Install packages","metadata":{}},{"cell_type":"code","source":"!pip install transformers\n!wget -O scibert_uncased.tar https://s3-us-west-2.amazonaws.com/ai2-s2-research/scibert/huggingface_pytorch/scibert_scivocab_uncased.tar\n!tar -xvf scibert_uncased.tar\n\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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-06-07T11:27:17.40031Z","iopub.execute_input":"2021-06-07T11:27:17.400691Z","iopub.status.idle":"2021-06-07T11:28:05.007187Z","shell.execute_reply.started":"2021-06-07T11:27:17.40061Z","shell.execute_reply":"2021-06-07T11:28:05.006195Z"},"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":{"execution":{"iopub.status.busy":"2021-06-08T13:41:49.915213Z","iopub.execute_input":"2021-06-08T13:41:49.915557Z","iopub.status.idle":"2021-06-08T13:41:50.606185Z","shell.execute_reply.started":"2021-06-08T13:41:49.915489Z","shell.execute_reply":"2021-06-08T13:41:50.60549Z"},"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 ./","metadata":{"execution":{"iopub.status.busy":"2021-06-07T11:28:05.825933Z","iopub.execute_input":"2021-06-07T11:28:05.826245Z","iopub.status.idle":"2021-06-07T11:28:06.475332Z","shell.execute_reply.started":"2021-06-07T11:28:05.826212Z","shell.execute_reply":"2021-06-07T11:28:06.474354Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Hyper-parameters","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\nMAX_SAMPLE = None # set a small number for experimentation, set None for production.\n","metadata":{"execution":{"iopub.status.busy":"2021-06-07T11:28:06.476987Z","iopub.execute_input":"2021-06-07T11:28:06.477343Z","iopub.status.idle":"2021-06-07T11:28:06.484422Z","shell.execute_reply.started":"2021-06-07T11:28:06.477305Z","shell.execute_reply":"2021-06-07T11:28:06.483616Z"},"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'\npaper_train_folder = '../input/coleridgeinitiative-show-us-the-data/train'\n\ntrain = pd.read_csv(train_path)\ntrain = train[:MAX_SAMPLE]\nprint(f'No. raw training rows: {len(train)}')","metadata":{"execution":{"iopub.status.busy":"2021-06-07T11:28:06.486888Z","iopub.execute_input":"2021-06-07T11:28:06.48714Z","iopub.status.idle":"2021-06-07T11:28:06.589827Z","shell.execute_reply.started":"2021-06-07T11:28:06.487116Z","shell.execute_reply":"2021-06-07T11:28:06.588935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07T11:28:06.591288Z","iopub.execute_input":"2021-06-07T11:28:06.591866Z","iopub.status.idle":"2021-06-07T11:28:06.965894Z","shell.execute_reply.started":"2021-06-07T11:28:06.591828Z","shell.execute_reply":"2021-06-07T11:28:06.964953Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"papers = {}\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-07T11:28:06.967151Z","iopub.execute_input":"2021-06-07T11:28:06.96766Z","iopub.status.idle":"2021-06-07T11:28:59.298873Z","shell.execute_reply.started":"2021-06-07T11:28:06.967622Z","shell.execute_reply":"2021-06-07T11:28:59.297823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Transform data to NER format","metadata":{}},{"cell_type":"code","source":"def 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\n\ndef find_sublist(big_list, small_list):\n    all_positions = []\n    for i in range(len(big_list) - len(small_list) + 1):\n        if small_list == big_list[i:i+len(small_list)]:\n            all_positions.append(i)\n    \n    return all_positions\n\ndef tag_sentence(sentence, labels): # requirement: both sentence and labels are already cleaned\n    sentence_words = sentence.split()\n    \n    if labels is not None and any(re.findall(f'\\\\b{label}\\\\b', sentence)\n                                  for label in labels): # positive sample\n        nes = ['O'] * len(sentence_words)\n        for label in labels:\n            label_words = label.split()\n\n            all_pos = find_sublist(sentence_words, label_words)\n            for pos in all_pos:\n                nes[pos] = 'B'\n                for i in range(pos+1, pos+len(label_words)):\n                    nes[i] = 'I'\n\n        return True, list(zip(sentence_words, nes))\n        \n    else: # negative sample\n        nes = ['O'] * len(sentence_words)\n        return False, list(zip(sentence_words, nes))","metadata":{"execution":{"iopub.status.busy":"2021-06-07T11:28:59.300944Z","iopub.execute_input":"2021-06-07T11:28:59.301311Z","iopub.status.idle":"2021-06-07T11:28:59.315334Z","shell.execute_reply.started":"2021-06-07T11:28:59.301275Z","shell.execute_reply":"2021-06-07T11:28:59.314363Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def augment_data(aug_labels, sentences):\n    #aug_labels is a list with tuples \n    #and on the first position we have the label and on the second the augmented label\n    for sentence in sentences:\n        for l in aug_labels:\n            sentence = sentence.replace(l[0], l[1])\n            \n    return sentences\n        \n\ndef create_aug_labels(papers, a_labels, random_aug=True):\n    #check if there is a way to match the external labels with those from this dataset\n    aug_labels = dict()\n    for i, id, dataset_label in train[['Id', 'dataset_label']].itertuples():\n        # paper\n        paper = papers[id]\n\n        # labels\n        labels = dataset_label.split('|')\n        labels = [clean_training_text(label) for label in labels]\n        \n        aug_labels[id] = list()\n        for l in labels:\n            if random_aug:\n                index = random.randint(0, len(a_labels)-1)\n                aug_labels[id].append((l, a_labels[index]))\n                \n    return aug_labels\n\n\ndef get_all_labels():\n    all_labels = []\n    for i, id, dataset_label in train[['Id', 'dataset_label']].itertuples():\n        # paper\n        paper = papers[id]\n        # labels\n        labels = dataset_label.split('|')\n        labels = [clean_training_text(label) for label in labels]\n        all_labels.extend(labels)\n    \n    return all_labels\n        ","metadata":{"execution":{"iopub.status.busy":"2021-06-07T11:28:59.31698Z","iopub.execute_input":"2021-06-07T11:28:59.317579Z","iopub.status.idle":"2021-06-07T11:28:59.32879Z","shell.execute_reply.started":"2021-06-07T11:28:59.317541Z","shell.execute_reply":"2021-06-07T11:28:59.327799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open('../input/aug-labels-dataset-names/datasets_bio.txt', 'r') as f:\n    extern_labels = f.readlines()\n    \naug_labels = create_aug_labels(papers, extern_labels, random_aug=True)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# all_labels = get_all_labels()\n# aug_labels = create_aug_labels(papers, all_labels, random_aug=True)","metadata":{"execution":{"iopub.status.busy":"2021-06-07T11:28:59.330322Z","iopub.execute_input":"2021-06-07T11:28:59.330781Z","iopub.status.idle":"2021-06-07T11:28:59.613819Z","shell.execute_reply.started":"2021-06-07T11:28:59.33074Z","shell.execute_reply":"2021-06-07T11:28:59.612949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"augment = True\n\ncnt_pos, cnt_neg = 0, 0 # number of sentences that contain/not contain labels\nner_data = []\n\npbar = tqdm(total=len(train))\nfor i, id, dataset_label in train[['Id', 'dataset_label']].itertuples():\n    # paper\n    paper = papers[id]\n    \n    # labels\n    labels = dataset_label.split('|')\n    labels = [clean_training_text(label) for label in labels]\n    \n    # sentences\n    sentences = set([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    sentences = [sentence for sentence in sentences if len(sentence) > 10] # only accept sentences with length > 10 chars\n    \n    if augment:\n            sentences_augment = augment_data(aug_labels[id], sentences)\n    # positive sample\n    for sentence in sentences:\n        is_positive, tags = tag_sentence(sentence, labels)\n        if is_positive:\n            cnt_pos += 1\n            ner_data.append(tags)\n        elif any(word in sentence.lower() for word in ['data', 'study']): \n            ner_data.append(tags)\n            cnt_neg += 1\n            \n    if augment:\n        for sentence_augment in sentences_augment:\n            is_positive_aug, tags_aug = tag_sentence(sentence_augment, labels)\n            if is_positive_aug:\n                cnt_pos += 1\n                ner_data.append(tags_aug)\n            elif any(word in sentence_augment.lower() for word in ['data', 'study']): \n                ner_data.append(tags_aug)\n                cnt_neg += 1\n        \n    # process bar\n    pbar.update(1)\n    pbar.set_description(f\"Training data size: {cnt_pos} positives + {cnt_neg} negatives\")\n\n# shuffling\nrandom.shuffle(ner_data)","metadata":{"execution":{"iopub.status.busy":"2021-06-07T11:33:11.499993Z","iopub.execute_input":"2021-06-07T11:33:11.500351Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"write data to file.","metadata":{}},{"cell_type":"code","source":"with open('train_ner.json', 'w') as f:\n    for row in ner_data:\n        words, nes = list(zip(*row))\n        row_json = {'tokens' : words, 'tags' : nes}\n        json.dump(row_json, f)\n        f.write('\\n')","metadata":{"execution":{"iopub.status.busy":"2021-06-07T12:38:37.523148Z","iopub.execute_input":"2021-06-07T12:38:37.523486Z","iopub.status.idle":"2021-06-07T12:38:37.811988Z","shell.execute_reply.started":"2021-06-07T12:38:37.523453Z","shell.execute_reply":"2021-06-07T12:38:37.810479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Fine-tune a BERT model for NER","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python ../input/kaggle-ner-utils/kaggle_run_ner.py \\\n--model_name_or_path 'bert-base-cased' \\\n--train_file './train_ner.json' \\\n--validation_file './train_ner.json' \\\n--num_train_epochs 1 \\\n--per_device_train_batch_size 8 \\\n--per_device_eval_batch_size 8 \\\n--save_steps 15000 \\\n--output_dir './output/scibert' \\\n--report_to 'none' \\\n--seed 123 \\\n--do_train ","metadata":{"execution":{"iopub.status.busy":"2021-06-07T12:38:37.813254Z","iopub.status.idle":"2021-06-07T12:38:37.813976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"After the tuning finishes, we should find our model in './output'.","metadata":{}},{"cell_type":"markdown","source":"BERT Prediction","metadata":{}}]}