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]