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98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
{
 "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
}