File size: 5,502 Bytes
e725d94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e607fd
 
e725d94
 
0e607fd
 
e725d94
 
0e607fd
 
e725d94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4f5467
e725d94
b4f5467
e725d94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c1f072
e725d94
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
"""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}")