brain-tumor-collection / brain-tumor-collection.py
benschill's picture
Update brain-tumor-collection.py
fe18ffc
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Collection of brain xray images for fine-grain classification."""
import datasets
import numpy as np
import pandas as pd
from pathlib import Path
import os
_CITATION = """\
@misc{kaggle-brain-tumor-classification,
title={Kaggle: Brain Tumor Classification (MRI)},
howpublished={\\url{https://www.kaggle.com/datasets/sartajbhuvaji/brain-tumor-classification-mri?resource=download}},
note = {Accessed: 2022-06-30},
}
"""
_DESCRIPTION = """\
This dataset is intended as a test case for classification tasks (4 different kinds of brain xrays). The dataset consists of almost 1400 JPEG images grouped into two splits - training and validation. Each split contains 4 categories labeled as n0~n3, each corresponding to a cancer result of the mrt.
| Label | Xray Category | Train Images | Validation Images |
| ----- | --------------------- | ------------ | ----------------- |
| n0 | glioma_tumor | 826 | 100 |
| n1 | meningioma_tumor | 822 | 115 |
| n2 | pituitary_tumor | 827 | 74 |
| n3 | no_tumor | 395 | 105 |
"""
_HOMEPAGE = "https://www.kaggle.com/datasets/sartajbhuvaji/brain-tumor-classification-mri?resource=download"
_LICENSE = "cc0-1.0"
_URLS = {
"original": "https://ibm.ent.box.com/index.php?rm=box_download_shared_file&shared_name=5ich3fqgpnbmkdho2eoe7fe4uwrplcfi&file_id=f_978363130854"
}
LABELS = [
"Glioma Tumor",
"Meningioma Tumor",
"Pituitary Tumor",
"No Tumor"
]
class BrainTumorCollectionGenerator(datasets.GeneratorBasedBuilder):
"""Collection of brain xray images for fine-grain classification."""
VERSION = datasets.Version("1.0.0")
BUILDER_CONFIGS = [
datasets.BuilderConfig(name="original", version=VERSION, description="Original JPEG files: images are 400x300 px or larger; ~550 MB"),
]
DEFAULT_CONFIG_NAME = "original"
def _info(self):
features = datasets.Features(
{
"image": datasets.Image(),
"label": datasets.ClassLabel(names=LABELS)
}
)
supervised_keys = ("image", "label")
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
supervised_keys=supervised_keys,
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
url = _URLS[self.config.name]
data_dir = dl_manager.download_and_extract(url)
print("Test"+data_dir)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"filepath": os.path.join(data_dir, "xrays", "training", "training"),
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"filepath": os.path.join(data_dir, "xrays", "validation", "validation"),
"split": "test",
},
),
]
def _generate_examples(self, filepath, split):
paths = list(Path(filepath).glob("**/*.jpg"))
data = []
for path in paths:
tumor_folder = str(path).split("/")[-2]
index = int(tumor_folder[1])
label = LABELS[index]
data.append({"file": str(path), "label": label})
df = pd.DataFrame(data)
print(df)
df.sort_values("file", inplace=True)
for idx_, row in df.iterrows():
yield idx_, {
"image": row["file"],
"label": row["label"]
}