fertility / fertility.py
mstz's picture
Upload fertility.py
9c1f072
"""Fertility"""
from typing import List
from functools import partial
import datasets
import pandas
VERSION = datasets.Version("1.0.0")
_BASE_FEATURE_NAMES = [
"season_of_sampling",
"age_at_time_of_sampling",
"has_had_childhood_diseases",
"has_had_serious_trauma",
"has_had_surgical_interventions",
"has_had_high_fevers_in_the_past_year",
"frequency_of_alcohol_consumption",
"smoking_frequency",
"number_of_sitting_hours_per_day",
"has_fertility_issues"
]
_ENCODING_DICS = {
"season_of_sampling" : {
-1: "winter",
-0.33: "spring",
+0.33: "summer",
+1: "fall",
},
"has_had_childhood_diseases" : {
1: True,
0: False
},
"has_had_serious_trauma" : {
1: True,
0: False
},
"has_had_surgical_interventions" : {
1: True,
0: False
},
"has_had_high_fevers_in_the_past_year" : {
1: "no",
0: "more than three months ago",
-1: "less than three months ago"
},
"smoking_frequency" : {
1: "daily",
0: "occasionally",
-1: "never"
},
"has_fertility_issues": {
"N": 0,
"O": 1
}
}
DESCRIPTION = "Fertility dataset from the UCI ML repository."
_HOMEPAGE = "https://archive.ics.uci.edu/ml/datasets/Fertility"
_URLS = ("https://archive.ics.uci.edu/ml/datasets/Fertility")
_CITATION = """
@misc{misc_fertility_244,
author = {Gil,David & Girela,Jose},
title = {{Fertility}},
year = {2013},
howpublished = {UCI Machine Learning Repository},
note = {{DOI}: \\url{10.24432/C5Z01Z}}
}"""
# Dataset info
urls_per_split = {
"train": "https://huggingface.co/datasets/mstz/fertility/raw/main/fertility_Diagnosis.txt"
}
features_types_per_config = {
"encoding": {
"feature": datasets.Value("string"),
"original_value": datasets.Value("string"),
"encoded_value": datasets.Value("int64"),
},
"fertility": {
"season_of_sampling": datasets.Value("string"),
"age_at_time_of_sampling": datasets.Value("int8"),
"has_had_childhood_diseases": datasets.Value("bool"),
"has_had_serious_trauma": datasets.Value("bool"),
"has_had_surgical_interventions": datasets.Value("bool"),
"has_had_high_fevers_in_the_past_year": datasets.Value("string"),
"frequency_of_alcohol_consumption": datasets.Value("float64"),
"smoking_frequency": datasets.Value("string"),
"number_of_sitting_hours_per_day": datasets.Value("float64"),
"has_fertility_issues": datasets.ClassLabel(num_classes=2, names=("no", "yes"))
}
}
features_per_config = {k: datasets.Features(features_types_per_config[k]) for k in features_types_per_config}
class FertilityConfig(datasets.BuilderConfig):
def __init__(self, **kwargs):
super(FertilityConfig, self).__init__(version=VERSION, **kwargs)
self.features = features_per_config[kwargs["name"]]
class Fertility(datasets.GeneratorBasedBuilder):
# dataset versions
DEFAULT_CONFIG = "fertility"
BUILDER_CONFIGS = [
FertilityConfig(name="encoding",
description="Encoding dictionaries for discrete features."),
FertilityConfig(name="fertility",
description="Fertility for binary classification.")
]
def _info(self):
info = datasets.DatasetInfo(description=DESCRIPTION, citation=_CITATION, homepage=_HOMEPAGE,
features=features_per_config[self.config.name])
return info
def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
downloads = dl_manager.download_and_extract(urls_per_split)
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": downloads["train"]})
]
def _generate_examples(self, filepath: str):
if self.config.name == "encoding":
data = self.encodings()
for row_id, row in data.iterrows():
data_row = dict(row)
yield row_id, data_row
else:
data = pandas.read_csv(filepath)
data = self.preprocess(data, config=self.config.name)
for row_id, row in data.iterrows():
data_row = dict(row)
yield row_id, data_row
def encodings(self):
data = [pandas.DataFrame([(feature, original_value, encoded_value)
for original_value, encoded_value in d.items()],
columns=["feature", "original_value", "encoded_value"])
for feature, d in _ENCODING_DICS.items()]
return data
def preprocess(self, data: pandas.DataFrame, config: str = DEFAULT_CONFIG) -> pandas.DataFrame:
data.columns = _BASE_FEATURE_NAMES
for feature in _ENCODING_DICS:
encoding_function = partial(self.encode, feature)
data.loc[:, feature] = data[feature].apply(encoding_function)
data.loc[:, "age_at_time_of_sampling"] = data["age_at_time_of_sampling"].apply(lambda x: 18 + x * 18)
data = data[list(features_types_per_config[config].keys())]
return data
def encode(self, feature, value):
if feature in _ENCODING_DICS:
return _ENCODING_DICS[feature][value]
raise ValueError(f"Unknown feature: {feature}")