File size: 8,684 Bytes
62dcf5b
b42d454
62dcf5b
b707e93
 
 
 
 
 
69d3bfe
b707e93
 
 
c04df20
 
b707e93
 
 
 
 
 
 
 
 
 
 
69d3bfe
b707e93
 
 
 
 
e38aeeb
b707e93
 
 
 
 
f81cea3
b707e93
b42d454
b707e93
df6a40d
92104bb
8c4b0a2
 
b42d454
 
 
 
 
 
 
 
 
fde2d1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b42d454
69d3bfe
 
 
 
b707e93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c04df20
51cae7d
 
b707e93
eca9f12
8443ee7
 
 
 
 
 
 
 
 
 
 
211dc42
8443ee7
 
 
 
 
8c4b0a2
8443ee7
 
 
 
 
 
 
 
 
211dc42
8443ee7
 
 
 
8c4b0a2
8443ee7
 
 
 
 
 
 
 
 
211dc42
8443ee7
 
 
 
8c4b0a2
8443ee7
 
 
 
b707e93
eca9f12
b707e93
 
 
071839c
8b0e745
70e927a
b707e93
 
 
 
 
 
8b0e745
3236b25
8b0e745
3236b25
8b0e745
68f3843
1fae491
 
b707e93
35e0cca
b707e93
1fae491
69d3bfe
9006e8f
b707e93
 
 
 
c04df20
b707e93
 
 
 
 
 
 
b42d454
 
dbaca55
 
 
 
 
 
91185bb
b42d454
 
 
 
 
 
 
dbaca55
b42d454
e38aeeb
 
 
b707e93
b42d454
b707e93
 
8c4b0a2
69e7ef9
d2fe9b6
b42d454
675957f
b707e93
d2fe9b6
33e2087
cfdaebd
26fc1e0
 
 
 
de21ad0
b127233
b42d454
b127233
b42d454
b127233
b42d454
 
 
205f0ce
b707e93
b42d454
 
 
 
b707e93
340083a
b42d454
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
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
from typing import List
from functools import partial

import datasets

import pandas


VERSION = datasets.Version("1.0.0")
_ORIGINAL_FEATURE_NAMES = [
    "age",
    "workclass",
    "final_weight",
    "education",
    "education-num",
    "marital_status",
    "occupation",
    "relationship",
    "race",
    "sex",
    "capital_gain",
    "capital_loss",
    "hours_per_week",
    "native_country",
    "threshold"
]
_BASE_FEATURE_NAMES = [
    "age",
    "capital_gain",
    "capital_loss",
    "education",
    "final_weight",
    "hours_worked_per_week",
    "marital_status",
    "native_country",
    "occupation",
    "race",
    "relationship",
    "is_male",
    "workclass",
    "over_threshold",
]
_ENCODING_DICS = {
    "is_male": {
            "Male": True,
            "Female": False
        }
}
_RACE_ENCODING = {
    "White": 0,
    "Black": 1,
    "Asian-Pac-Islander": 2,
    "Amer-Indian-Eskimo": 3,
    "Other": 4,
}
_EDUCATION_ENCODING = {
	"Preschool": 0,
	"1st-4th": 1,
	"5th-6th": 2,
	"7th-8th": 3,
	"9th": 4,
	"10th": 5,
	"11th": 6,
	"12th": 7,
	"HS-grad": 8,
	"Assoc-acdm": 9,
	"Assoc-voc": 10,
	"Some-college": 11,
    "Bachelors": 12,
	"Masters": 13,
	"Doctorate": 14,
	"Prof-school": 15
}

DESCRIPTION = "Adult dataset from the UCI ML repository."
_HOMEPAGE = "https://archive.ics.uci.edu/ml/datasets/Adult"
_URLS = ("https://huggingface.co/datasets/mstz/adult/raw/adult.csv")
_CITATION = """
@inproceedings{DBLP:conf/kdd/Kohavi96,
  author    = {Ron Kohavi},
  editor    = {Evangelos Simoudis and
               Jiawei Han and
               Usama M. Fayyad},
  title     = {Scaling Up the Accuracy of Naive-Bayes Classifiers: {A} Decision-Tree
               Hybrid},
  booktitle = {Proceedings of the Second International Conference on Knowledge Discovery
               and Data Mining (KDD-96), Portland, Oregon, {USA}},
  pages     = {202--207},
  publisher = {{AAAI} Press},
  year      = {1996},
  url       = {http://www.aaai.org/Library/KDD/1996/kdd96-033.php},
  timestamp = {Mon, 05 Jun 2017 13:20:21 +0200},
  biburl    = {https://dblp.org/rec/conf/kdd/Kohavi96.bib},
  bibsource = {dblp computer science bibliography, https://dblp.org}
}"""

# Dataset info
urls_per_split = {
    "train": "https://huggingface.co/datasets/mstz/adult/raw/main/adult_tr.csv", 
    "test": "https://huggingface.co/datasets/mstz/adult/raw/main/adult_ts.csv"
}
features_types_per_config = {
    "encoding": {
        "feature": datasets.Value("string"),
        "original_value": datasets.Value("string"),
        "encoded_value": datasets.Value("int64"),
    },
    "income": {
        "age": datasets.Value("int64"),
        "capital_gain": datasets.Value("float64"),
        "capital_loss": datasets.Value("float64"),
        "education": datasets.Value("int8"),
        "final_weight": datasets.Value("int64"),
        "hours_worked_per_week": datasets.Value("int64"),
        "marital_status": datasets.Value("string"),
        "native_country": datasets.Value("string"),
        "occupation": datasets.Value("string"),
        "race": datasets.Value("string"),
        "relationship": datasets.Value("string"),
        "is_male": datasets.Value("bool"),
        "workclass": datasets.Value("string"),
        "over_threshold": datasets.ClassLabel(num_classes=2, names=("no", "yes"))
    },
    "income-no race": {
        "age": datasets.Value("int64"),
        "capital_gain": datasets.Value("float64"),
        "capital_loss": datasets.Value("float64"),
        "education": datasets.Value("int64"),
        "final_weight": datasets.Value("int64"),
        "hours_worked_per_week": datasets.Value("int64"),
        "marital_status": datasets.Value("string"),
        "native_country": datasets.Value("string"),
        "occupation": datasets.Value("string"),
        "relationship": datasets.Value("string"),
        "is_male": datasets.Value("bool"),
        "workclass": datasets.Value("string"),
        "over_threshold": datasets.ClassLabel(num_classes=2, names=("no", "yes"))
    },
    "race": {
        "age": datasets.Value("int64"),
        "capital_gain": datasets.Value("float64"),
        "capital_loss": datasets.Value("float64"),
        "education": datasets.Value("int64"),
        "final_weight": datasets.Value("int64"),
        "hours_worked_per_week": datasets.Value("int64"),
        "marital_status": datasets.Value("string"),
        "native_country": datasets.Value("string"),
        "occupation": datasets.Value("string"),
        "relationship": datasets.Value("string"),
        "is_male": datasets.Value("bool"),
        "workclass": datasets.Value("string"),
        "over_threshold": datasets.Value("int8"),
        "race": datasets.ClassLabel(num_classes=5, names=["White", "Black", "Asian-Pac-Islander", "Amer-Indian-Eskimo", "Other"])
    }
}
features_per_config = {k: datasets.Features(features_types_per_config[k]) for k in features_types_per_config}


class AdultConfig(datasets.BuilderConfig):
    def __init__(self, **kwargs):
        super(AdultConfig, self).__init__(version=VERSION, **kwargs)
        self.features = features_per_config[kwargs["name"]]


class Adult(datasets.GeneratorBasedBuilder):
    # dataset versions
    DEFAULT_CONFIG = "income"
    BUILDER_CONFIGS = [
        AdultConfig(name="income",
                    description="Adult for income threshold binary classification."),
        AdultConfig(name="income-no race",
                    description="Adult for income threshold binary classification, race excluded from features."),
        AdultConfig(name="race", 
                    description="Adult for race (multiclass) classification."),
        AdultConfig(name="encoding",
                    description="Encoding dictionaries for discrete features.")
    ]


    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"]}),
            datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": downloads["test"]}),
        ]
    
    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([("education", original_value, encoded_value)
                                 for original_value, encoded_value in _EDUCATION_ENCODING.items()],
                                columns=["feature", "original_value", "encoded_value"])

        return data


    def preprocess(self, data: pandas.DataFrame, config: str = DEFAULT_CONFIG) -> pandas.DataFrame:
        data.drop("education", axis="columns", inplace=True)
        data = data.rename(columns={"threshold": "over_threshold", "sex": "is_male"})

        data = data[["age", "capital_gain", "capital_loss", "education-num", "final_weight",
                     "hours_per_week", "marital_status", "native_country", "occupation",
                     "race", "relationship", "is_male", "workclass", "over_threshold"]]
        data.columns = _BASE_FEATURE_NAMES

        for feature in _ENCODING_DICS:
            encoding_function = partial(self.encode, feature)
            data.loc[:, feature] = data[feature].apply(encoding_function)
        

        if config == "income":
            return data[list(features_types_per_config["income"].keys())]
        elif config == "income-no race":
            return data[list(features_types_per_config["income-no race"].keys())]
        elif config =="race":
            data.loc[:, "race"] = data.race.apply(self.encode_race)
            data = data[list(features_types_per_config["race"].keys())]

            return data
    
    def encode(self, feature, value):
        if feature in _ENCODING_DICS:
            return _ENCODING_DICS[feature][value]
        raise ValueError(f"Unknown feature: {feature}")
    
    def encode_race(self, race):
        return _RACE_ENCODING[race]