"""Diva: A Fraud Detection Dataset""" from typing import List 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_per_week", "marital_status", "native_country", "occupation", "race", "relationship", "sex", "workclass", "threshold", ] 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 = { "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_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"), "sex": datasets.Value("string"), "workclass": datasets.Value("string"), "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_per_week": datasets.Value("int64"), "marital_status": datasets.Value("string"), "native_country": datasets.Value("string"), "occupation": datasets.Value("string"), "relationship": datasets.Value("string"), "sex": datasets.Value("string"), "workclass": datasets.Value("string"), "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_per_week": datasets.Value("int64"), "marital_status": datasets.Value("string"), "native_country": datasets.Value("string"), "occupation": datasets.Value("string"), "relationship": datasets.Value("string"), "sex": datasets.Value("string"), "workclass": datasets.Value("string"), "over_threshold": datasets.Value("string"), "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."), ] def _info(self): if self.config.name not in features_per_config: raise ValueError(f"Unknown configuration: {self.config.name}") 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): 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 preprocess(self, data: pandas.DataFrame, config: str = "income") -> pandas.DataFrame: data.drop("education", axis="columns", inplace=True) data = data[["age", "capital_gain", "capital_loss", "education-num", "final_weight", "hours_per_week", "marital_status", "native_country", "occupation", "race", "relationship", "sex", "workclass", "threshold"]] data.columns = _BASE_FEATURE_NAMES # binarize features data.loc[:, "sex"] = data.sex.apply(self.encode_sex) if config == "income": return self.income_preprocessing(data) elif config == "income-no race": return self.income_norace_preprocessing(data) elif config =="race": return self.race_preprocessing(data) else: raise ValueError(f"Unknown config: {config}") def income_preprocessing(self, data: pandas.DataFrame) -> pandas.DataFrame: data = data[list(features_types_per_config["income"].keys())] return data def income_norace_preprocessing(self, data: pandas.DataFrame) -> pandas.DataFrame: data = data[list(features_types_per_config["income-no race"].keys())] return data def race_preprocessing(self, data: pandas.DataFrame) -> pandas.DataFrame: features = list(features_types_per_config["race"].keys()) features[features.index("over_threshold")] = "threshold" data.loc[:, "race"] = data.race.apply(self.encode_race) data = data[features] data.columns = ["age", "capital_gain", "capital_loss", "education", "final_weight", "hours_per_week", "marital_status", "native_country", "occupation", "relationship", "sex", "workclass", "over_threshold", "race"] return data def encode_race(self, race): return self.race_encoding_dic()[race] def decode_race(self, code): return self.race_decoding_dic()[code] def race_decoding_dic(self): return { 0: "White", 1: "Black", 2: "Asian-Pac-Islander", 3: "Amer-Indian-Eskimo", 4: "Other", } def race_encoding_dic(self): return { "White": 0, "Black": 1, "Asian-Pac-Islander": 2, "Amer-Indian-Eskimo": 3, "Other": 4, } def encode_sex(self, sex): return self.sex_encoding_dic()[sex] def decode_sex(self, code): return self.sex_decoding_dic()[code] def sex_encoding_dic(self): return { "Male": 0, "Female": 1 } def sex_decoding_dic(self): return { 0: "Male", 1: "Female" }