{ "cells": [ { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# import the package\n", "import numpy as np\n", "import pandas as pd\n", "import datasets\n", "import evaluate\n", "from datasets import DatasetDict, Dataset\n", "from transformers import AutoTokenizer, Trainer, BertForSequenceClassification\n", "import torch\n", "from accelerate import Accelerator" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Attention: \n", "\n", "This file is used to ranking the response. It will calculate the probability for each sample_answer and return the most probability one and the index of it. \n", "\n", "The file only contains answers to one question is recommended or we need to split the dataframe manually.\n", "\n", "The input of the function is the path of the file and the file of the pretrained model and corresponding tokenizer." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "# load the data\n", "\n", "path = 'C:/Users/cxz55/Desktop/UCL/term2/COMP087/cw/data_nlp_porject' #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n", "file_name = 'five_responses.csv' #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n", "\n", "def load_data(path,file_name):\n", "\n", " path = '/'.join([path,file_name])\n", " test_response = pd.read_csv(path)\n", " return test_response" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Some weights of BertForSequenceClassification were not initialized from the model checkpoint at dmis-lab/biobert-v1.1 and are newly initialized: ['classifier.bias', 'classifier.weight']\n", "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n" ] } ], "source": [ "# give the model and corresponfing tokenizer\n", "\n", "# the base models we used are:\n", "# \"emilyalsentzer/Bio_ClinicalBERT\" \n", "# \"dmis-lab/biobert-v1.1\"\n", "# \"microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext\"\n", "# \"allenai/scibert_scivocab_uncased\"\n", "# \"bionlp/bluebert_pubmed_mimic_uncased_L-12_H-768_A-12\"\n", "\n", "# model_name = 'dmis-lab/biobert-v1.1' #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n", "# model = BertForSequenceClassification.from_pretrained(model_name, num_labels=2)\n", "\n", "# tokenizer_name = 'dmis-lab/biobert-v1.1' #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n", "# tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "# def tokenize_function(data):\n", "# return tokenizer(data['Question'],data['Answer'],padding='max_length',truncation=True,max_length=128)\n", "\n", "# def compute_metrics(eval_preds):\n", "# metric = evaluate.load(\"accuracy\")\n", "# x,y = eval_preds\n", "# preds = np.argmax(x, -1)\n", "# return metric.compute(predictions=preds, references=y)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# # add device\n", "# accelerator = Accelerator()\n", "# device = accelerator.device" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "# build the model\n", "# trainer = Trainer(\n", "# model=model.to(device),\n", "# # args=training_args,\n", "# # data_collator=data_collator,\n", "# tokenizer=tokenizer,\n", "# compute_metrics=compute_metrics,\n", "# )" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "# # dealing with data: from dataframe transform into DatasetDict\n", "# data_set = load_data(path,file_name)\n", "# data_dict = Dataset.from_pandas(data_set)\n", "# data_dict_token = data_dict.map(tokenize_function, batched=8)\n", "# # make prediction\n", "# prediction = trainer.predict(data_dict_token)\n", "# logits = torch.tensor(prediction.predictions)\n", "# prob = torch.softmax(logits,dim=1)\n", "# right_prob = prob[:,1]\n", "# prob_list = right_prob.tolist()\n" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "def prob_position(path, file_name, model_name,tokenizer_name):\n", "\n", " # the list of model name:\n", " # the base models we used are:\n", " # \"emilyalsentzer/Bio_ClinicalBERT\" \n", " # \"dmis-lab/biobert-v1.1\"\n", " # \"microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext\"\n", " # \"allenai/scibert_scivocab_uncased\"\n", " # \"bionlp/bluebert_pubmed_mimic_uncased_L-12_H-768_A-12\"\n", "\n", " model = BertForSequenceClassification.from_pretrained(model_name, num_labels=2)\n", " tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)\n", "\n", " # define the tokenizing map and the metrics\n", " def tokenize_function(data):\n", " return tokenizer(data['Question'],data['Answer'],padding='max_length',truncation=True,max_length=128)\n", " def compute_metrics(eval_preds):\n", " metric = evaluate.load(\"accuracy\")\n", " x,y = eval_preds\n", " preds = np.argmax(x, -1)\n", " return metric.compute(predictions=preds, references=y)\n", "\n", " # add device\n", " accelerator = Accelerator()\n", " device = accelerator.device\n", "\n", " # build trainer\n", " trainer = Trainer(\n", " model=model.to(device),\n", " # args=training_args,\n", " # data_collator=data_collator,\n", " tokenizer=tokenizer,\n", " compute_metrics=compute_metrics,\n", " )\n", "\n", " # dealing with data: from dataframe transform into DatasetDict\n", " data_set = load_data(path,file_name)\n", " data_dict = Dataset.from_pandas(data_set)\n", " data_dict_token = data_dict.map(tokenize_function, batched=8)\n", " \n", " # make prediction\n", " prediction = trainer.predict(data_dict_token)\n", "\n", " # transform it into probability\n", " logits = torch.tensor(prediction.predictions)\n", " prob = torch.softmax(logits,dim=1)\n", "\n", " # the probability the answer is correct\n", " right_prob = prob[:,1]\n", " prob_list = right_prob.tolist()\n", "\n", " max_value = max(prob_list)\n", " max_index = prob_list.index(max_value) + 1\n", "\n", " print(f'\\n##############RESULT####################\\nThe index of the most proper answer is: {max_index}\\nThe probability it is correct is: {max_value}')\n", "\n", " return max_value,max_index" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "loading configuration file config.json from cache at C:\\Users\\cxz55/.cache\\huggingface\\hub\\models--dmis-lab--biobert-v1.1\\snapshots\\551ca18efd7f052c8dfa0b01c94c2a8e68bc5488\\config.json\n", "Model config BertConfig {\n", " \"architectures\": [\n", " \"BertModel\"\n", " ],\n", " \"attention_probs_dropout_prob\": 0.1,\n", " \"classifier_dropout\": null,\n", " \"gradient_checkpointing\": false,\n", " \"hidden_act\": \"gelu\",\n", " \"hidden_dropout_prob\": 0.1,\n", " \"hidden_size\": 768,\n", " \"initializer_range\": 0.02,\n", " \"intermediate_size\": 3072,\n", " \"layer_norm_eps\": 1e-12,\n", " \"max_position_embeddings\": 512,\n", " \"model_type\": \"bert\",\n", " \"num_attention_heads\": 12,\n", " \"num_hidden_layers\": 12,\n", " \"pad_token_id\": 0,\n", " \"position_embedding_type\": \"absolute\",\n", " \"transformers_version\": \"4.24.0\",\n", " \"type_vocab_size\": 2,\n", " \"use_cache\": true,\n", " \"vocab_size\": 28996\n", "}\n", "\n", "loading weights file pytorch_model.bin from cache at C:\\Users\\cxz55/.cache\\huggingface\\hub\\models--dmis-lab--biobert-v1.1\\snapshots\\551ca18efd7f052c8dfa0b01c94c2a8e68bc5488\\pytorch_model.bin\n", "All model checkpoint weights were used when initializing BertForSequenceClassification.\n", "\n", "Some weights of BertForSequenceClassification were not initialized from the model checkpoint at dmis-lab/biobert-v1.1 and are newly initialized: ['classifier.bias', 'classifier.weight']\n", "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n", "loading configuration file config.json from cache at C:\\Users\\cxz55/.cache\\huggingface\\hub\\models--dmis-lab--biobert-v1.1\\snapshots\\551ca18efd7f052c8dfa0b01c94c2a8e68bc5488\\config.json\n", "Model config BertConfig {\n", " \"_name_or_path\": \"dmis-lab/biobert-v1.1\",\n", " \"architectures\": [\n", " \"BertModel\"\n", " ],\n", " \"attention_probs_dropout_prob\": 0.1,\n", " \"classifier_dropout\": null,\n", " \"gradient_checkpointing\": false,\n", " \"hidden_act\": \"gelu\",\n", " \"hidden_dropout_prob\": 0.1,\n", " \"hidden_size\": 768,\n", " \"initializer_range\": 0.02,\n", " \"intermediate_size\": 3072,\n", " \"layer_norm_eps\": 1e-12,\n", " \"max_position_embeddings\": 512,\n", " \"model_type\": \"bert\",\n", " \"num_attention_heads\": 12,\n", " \"num_hidden_layers\": 12,\n", " \"pad_token_id\": 0,\n", " \"position_embedding_type\": \"absolute\",\n", " \"transformers_version\": \"4.24.0\",\n", " \"type_vocab_size\": 2,\n", " \"use_cache\": true,\n", " \"vocab_size\": 28996\n", "}\n", "\n", "loading file vocab.txt from cache at C:\\Users\\cxz55/.cache\\huggingface\\hub\\models--dmis-lab--biobert-v1.1\\snapshots\\551ca18efd7f052c8dfa0b01c94c2a8e68bc5488\\vocab.txt\n", "loading file tokenizer.json from cache at None\n", "loading file added_tokens.json from cache at None\n", "loading file special_tokens_map.json from cache at C:\\Users\\cxz55/.cache\\huggingface\\hub\\models--dmis-lab--biobert-v1.1\\snapshots\\551ca18efd7f052c8dfa0b01c94c2a8e68bc5488\\special_tokens_map.json\n", "loading file tokenizer_config.json from cache at C:\\Users\\cxz55/.cache\\huggingface\\hub\\models--dmis-lab--biobert-v1.1\\snapshots\\551ca18efd7f052c8dfa0b01c94c2a8e68bc5488\\tokenizer_config.json\n", "loading configuration file config.json from cache at C:\\Users\\cxz55/.cache\\huggingface\\hub\\models--dmis-lab--biobert-v1.1\\snapshots\\551ca18efd7f052c8dfa0b01c94c2a8e68bc5488\\config.json\n", "Model config BertConfig {\n", " \"_name_or_path\": \"dmis-lab/biobert-v1.1\",\n", " \"architectures\": [\n", " \"BertModel\"\n", " ],\n", " \"attention_probs_dropout_prob\": 0.1,\n", " \"classifier_dropout\": null,\n", " \"gradient_checkpointing\": false,\n", " \"hidden_act\": \"gelu\",\n", " \"hidden_dropout_prob\": 0.1,\n", " \"hidden_size\": 768,\n", " \"initializer_range\": 0.02,\n", " \"intermediate_size\": 3072,\n", " \"layer_norm_eps\": 1e-12,\n", " \"max_position_embeddings\": 512,\n", " \"model_type\": \"bert\",\n", " \"num_attention_heads\": 12,\n", " \"num_hidden_layers\": 12,\n", " \"pad_token_id\": 0,\n", " \"position_embedding_type\": \"absolute\",\n", " \"transformers_version\": \"4.24.0\",\n", " \"type_vocab_size\": 2,\n", " \"use_cache\": true,\n", " \"vocab_size\": 28996\n", "}\n", "\n", "loading configuration file config.json from cache at C:\\Users\\cxz55/.cache\\huggingface\\hub\\models--dmis-lab--biobert-v1.1\\snapshots\\551ca18efd7f052c8dfa0b01c94c2a8e68bc5488\\config.json\n", "Model config BertConfig {\n", " \"_name_or_path\": \"dmis-lab/biobert-v1.1\",\n", " \"architectures\": [\n", " \"BertModel\"\n", " ],\n", " \"attention_probs_dropout_prob\": 0.1,\n", " \"classifier_dropout\": null,\n", " \"gradient_checkpointing\": false,\n", " \"hidden_act\": \"gelu\",\n", " \"hidden_dropout_prob\": 0.1,\n", " \"hidden_size\": 768,\n", " \"initializer_range\": 0.02,\n", " \"intermediate_size\": 3072,\n", " \"layer_norm_eps\": 1e-12,\n", " \"max_position_embeddings\": 512,\n", " \"model_type\": \"bert\",\n", " \"num_attention_heads\": 12,\n", " \"num_hidden_layers\": 12,\n", " \"pad_token_id\": 0,\n", " \"position_embedding_type\": \"absolute\",\n", " \"transformers_version\": \"4.24.0\",\n", " \"type_vocab_size\": 2,\n", " \"use_cache\": true,\n", " \"vocab_size\": 28996\n", "}\n", "\n", "No `TrainingArguments` passed, using `output_dir=tmp_trainer`.\n", "PyTorch: setting up devices\n", "The default value for the training argument `--report_to` will change in v5 (from all installed integrations to none). In v5, you will need to use `--report_to all` to get the same behavior as now. You should start updating your code and make this info disappear :-).\n", "The following columns in the test set don't have a corresponding argument in `BertForSequenceClassification.forward` and have been ignored: Unnamed: 0, Context, Label, Question, Answer. If Unnamed: 0, Context, Label, Question, Answer are not expected by `BertForSequenceClassification.forward`, you can safely ignore this message.\n", "***** Running Prediction *****\n", " Num examples = 300\n", " Batch size = 8\n", "You're using a BertTokenizerFast tokenizer. Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the text followed by a call to the `pad` method to get a padded encoding.\n", "100%|██████████| 38/38 [00:01<00:00, 25.79it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "##############RESULT####################\n", "The index of the most proper answer is: 54\n", "The probability it is correct is: 0.6013683676719666\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] }, { "data": { "text/plain": [ "(0.6013683676719666, 54)" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "prob_position(path,file_name,\"dmis-lab/biobert-v1.1\",\"dmis-lab/biobert-v1.1\")" ] } ], "metadata": { "kernelspec": { "display_name": "pytorch", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)]" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "9cf8428aa180ee23632ed7df20f7a595edda7c60e668686876baf89d702ea1cf" } } }, "nbformat": 4, "nbformat_minor": 2 }