BLURB / BLURB.py
Dr. Jorge Abreu Vicente
Solve _self typo
43ccb0d
raw
history blame
7.17 kB
"""Loading script for the BLURB (Biomedical Language Understanding and Reasoning Benchmark)
benchmark for biomedical NLP."""
import json
from pathlib import Path
import datasets
import shutil
_CITATION = """\
@article{2022,
title={Domain-Specific Language Model Pretraining for Biomedical Natural Language Processing},
volume={3},
ISSN={2637-8051},
url={http://dx.doi.org/10.1145/3458754},
DOI={10.1145/3458754},
number={1},
journal={ACM Transactions on Computing for Healthcare},
publisher={Association for Computing Machinery (ACM)},
author={Gu, Yu and Tinn, Robert and Cheng, Hao and Lucas, Michael and Usuyama, Naoto and Liu, Xiaodong and Naumann, Tristan and Gao, Jianfeng and Poon, Hoifung},
year={2022},
month={Jan},
pages={1–23}
}
"""
_DESCRIPTION = """BLURB (Biomedical Language Understanding and Reasoning Benchmark.)
is a comprehensive benchmark for biomedical NLP, with 13 biomedical NLP datasets in 6
tasks (NER, PICO, Relation Extraction, Sentence similarity, document classification, question answering).
Our aim is to facilitate investigations of biomedical natural language processing
with a specific focus on language model pretraining and to help accelerate progress in universal Biomedical
NLP applications. The table below compares the datasets comprising BLURB versus the various datasets used in
previous Biomedical and Clinical BERT language models."""
_HOMEPAGE = "https://microsoft.github.io/BLURB/index.html"
_LICENSE = "TBD"
_VERSION = "1.0.0"
DATA_DIR = "blurb/"
logger = datasets.logging.get_logger(__name__)
CITATION_BC5_CHEM = """@article{article,
author = {Li, Jiao and Sun, Yueping and Johnson, Robin and Sciaky, Daniela and Wei, Chih-Hsuan and Leaman, Robert and Davis, Allan Peter and Mattingly, Carolyn and Wiegers, Thomas and lu, Zhiyong},
year = {2016},
month = {05},
pages = {baw068},
title = {BioCreative V CDR task corpus: a resource for chemical disease relation extraction},
volume = {2016},
journal = {Database},
doi = {10.1093/database/baw068}
}
"""
class BlurbConfig(datasets.BuilderConfig):
"""BuilderConfig for BLURB."""
def __init__(self, task, data_url, citation, label_classes=("False", "True"), **kwargs):
"""BuilderConfig for BLURB.
Args:
task: `string` task the dataset is used for: 'ner', 'pico', 'rel-ext', 'sent-sim', 'doc-clas', 'qa'
features: `list[string]`, list of the features that will appear in the
feature dict. Should not include "label".
data_url: `string`, url to download the data files from.
citation: `string`, citation for the data set.
url: `string`, url for information about the data set.
label_classes: `list[string]`, the list of classes for the label if the
label is present as a string. Non-string labels will be cast to either
'False' or 'True'.
**kwargs: keyword arguments forwarded to super.
"""
# Version history:
super(BlurbConfig, self).__init__(version=datasets.Version(_VERSION), **kwargs)
self.task = task
self.label_classes = label_classes
self.data_url = data_url
self.citation = citation
if self.task == 'ner':
self.features = datasets.Features(
{"id": datasets.Value("string"),
"tokens": datasets.Sequence(datasets.Value("string")),
"ner_tags": datasets.Sequence(
datasets.features.ClassLabel(names=self.label_classes)
)}
)
self.base_url = f"{self.data_url}{self.name}/"
self.urls = {
"train": f"{self.base_url}{'train.tsv'}",
"validation": f"{self.base_url}{'devel.tsv'}",
"test": f"{self.base_url}{'test.tsv'}"
}
class Blurb(datasets.GeneratorBasedBuilder):
"""BLURB benchmark dataset for Biomedical Language Understanding and Reasoning Benchmark."""
BUILDER_CONFIGS = [
BlurbConfig(name='BC5CDR-chem-IOB', task='ner', label_classes=['O', 'B-Chemical', 'I-Chemical'],
data_url = "https://github.com/cambridgeltl/MTL-Bioinformatics-2016/tree/master/data/",
description='BC5-CHEM',
citation=CITATION_BC5_CHEM)
]
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"id": datasets.Value("string"),
"tokens": datasets.Sequence(datasets.Value("string")),
"ner_tags": datasets.Sequence(
datasets.features.ClassLabel(
names=[
"O",
"B-Chemical",
"I-Chemical",
]
)
),
}
),
supervised_keys=None,
homepage=_HOMEPAGE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
if self.config.task == 'ner':
downloaded_files = dl_manager.download_and_extract(self.config.urls)
return self._ner_split_generator(downloaded_files)
def _generate_examples(self, filepath):
print("Before the download")
logger.info("⏳ Generating examples from = %s", filepath)
if self.config.task == 'ner':
self._ner_example_generator(filepath)
def _ner_split_generator(self, downloaded_files):
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN,
gen_kwargs={"filepath": downloaded_files["train"]}),
datasets.SplitGenerator(name=datasets.Split.VALIDATION,
gen_kwargs={"filepath": downloaded_files["validation"]}),
datasets.SplitGenerator(name=datasets.Split.TEST,
gen_kwargs={"filepath": downloaded_files["test"]}),
]
def _ner_example_generator(self, filepath):
with open(filepath, encoding="utf-8") as f:
guid = 0
tokens = []
ner_tags = []
for line in f:
if line == "" or line == "\n":
if tokens:
yield guid, {
"id": str(guid),
"tokens": tokens,
"ner_tags": ner_tags,
}
guid += 1
tokens = []
ner_tags = []
else:
# tokens are tab separated
splits = line.split("\t")
tokens.append(splits[0])
ner_tags.append(splits[1].rstrip())
# last example
yield guid, {
"id": str(guid),
"tokens": tokens,
"ner_tags": ner_tags,
}