"""Compas Dataset""" from typing import List from functools import partial import datetime import datasets import pandas VERSION = datasets.Version("1.0.0") _ORIGINAL_FEATURE_NAMES = [ "id", "name", "first", "last", "compas_screening_date", "sex", "dob", "age", "age_cat", "race", "juv_fel_count", "decile_score", "juv_misd_count", "juv_other_count", "priors_count", "days_b_screening_arrest", "c_jail_in", "c_jail_out", "c_case_number", "c_offense_date", "c_arrest_date", "c_days_from_compas", "c_charge_degree", "c_charge_desc", "is_recid", "r_case_number", "r_charge_degree", "r_days_from_arrest", "r_offense_date", "r_charge_desc", "r_jail_in", "r_jail_out", "violent_recid", "is_violent_recid", "vr_case_number", "vr_charge_degree", "vr_offense_date", "vr_charge_desc", "type_of_assessment", "decile_score", "score_text", "screening_date", "v_type_of_assessment", "v_decile_score", "v_score_text", "v_screening_date", "in_custody", "out_custody", "priors_count", "start", "end", "event", "two_year_recid", "two_year_recid" ] _BASE_FEATURE_NAMES = [ "sex", "age", "race", "number_of_juvenile_fellonies", "decile_score", "number_of_juvenile_misdemeanors", "number_of_other_juvenile_offenses", "number_of_prior_offenses", "days_before_screening_arrest", "is_recidivous", "days_in_custody", "is_violent_recidivous", "violence_decile_score", "two_year_recidivous", ] _ENCODING_DICS = { "sex": { "Male": 1, "Female": 0 }, "race": { "Caucasian": 0, "African-American": 1, "Hispanic": 2, "Asian": 3, "Other": 4, "Native American": 5, } } DESCRIPTION = "COMPAS dataset for recidivism prediction." _HOMEPAGE = "https://github.com/propublica/compas-analysis" _URLS = ("https://huggingface.co/datasets/mstz/compas/raw/main/compas-scores-two-years-violent.csv") _CITATION = """""" # Dataset info urls_per_split = { "train": "https://huggingface.co/datasets/mstz/compas/raw/main/compas-scores-two-years-violent.csv", } features_types_per_config = { "encoding": { "feature": datasets.Value("string"), "original_value": datasets.Value("string"), "encoded_value": datasets.Value("int8"), }, "two-years-recidividity": { "is_male": datasets.Value("bool"), "age": datasets.Value("int64"), "race": datasets.Value("string"), "number_of_juvenile_fellonies": datasets.Value("int64"), "decile_score": datasets.Value("int64"), "number_of_juvenile_misdemeanors": datasets.Value("int64"), "number_of_other_juvenile_offenses": datasets.Value("int64"), "number_of_prior_offenses": datasets.Value("int64"), "days_before_screening_arrest": datasets.Value("int64"), "is_recidivous": datasets.Value("bool"), "days_in_custody": datasets.Value("int64"), "is_violent_recidivous": datasets.Value("bool"), "violence_decile_score": datasets.Value("int64"), "two_year_recidivous": datasets.ClassLabel(num_classes=2, names=("no", "yes")), }, "two-years-recidividity-no-race": { "is_male": datasets.Value("bool"), "age": datasets.Value("int64"), "number_of_juvenile_fellonies": datasets.Value("int64"), "decile_score": datasets.Value("int64"), "number_of_juvenile_misdemeanors": datasets.Value("int64"), "number_of_other_juvenile_offenses": datasets.Value("int64"), "number_of_prior_offenses": datasets.Value("int64"), "days_before_screening_arrest": datasets.Value("int64"), "is_recidivous": datasets.Value("bool"), "days_in_custody": datasets.Value("int64"), "is_violent_recidivous": datasets.Value("bool"), "violence_decile_score": datasets.Value("int64"), "two_year_recidivous": datasets.ClassLabel(num_classes=2, names=("no", "yes")), }, "priors-prediction": { "is_male": datasets.Value("bool"), "age": datasets.Value("int64"), "race": datasets.Value("string"), "number_of_juvenile_fellonies": datasets.Value("int64"), "decile_score": datasets.Value("int64"), "number_of_juvenile_misdemeanors": datasets.Value("int64"), "number_of_other_juvenile_offenses": datasets.Value("int64"), "days_before_screening_arrest": datasets.Value("int64"), "is_recidivous": datasets.Value("bool"), "days_in_custody": datasets.Value("int64"), "is_violent_recidivous": datasets.Value("bool"), "violence_decile_score": datasets.Value("int64"), "two_year_recidivous": datasets.Value("int64"), "number_of_prior_offenses": datasets.Value("int64") }, "priors-prediction-no-race": { "is_male": datasets.Value("bool"), "age": datasets.Value("int64"), "number_of_juvenile_fellonies": datasets.Value("int64"), "decile_score": datasets.Value("int64"), "number_of_juvenile_misdemeanors": datasets.Value("int64"), "number_of_other_juvenile_offenses": datasets.Value("int64"), "days_before_screening_arrest": datasets.Value("int64"), "is_recidivous": datasets.Value("bool"), "days_in_custody": datasets.Value("int64"), "is_violent_recidivous": datasets.Value("bool"), "violence_decile_score": datasets.Value("int64"), "two_year_recidivous": datasets.Value("int64"), "number_of_prior_offenses": datasets.Value("int64"), }, "race": { "is_male": datasets.Value("bool"), "age": datasets.Value("int64"), "number_of_juvenile_fellonies": datasets.Value("int64"), "decile_score": datasets.Value("int64"), "number_of_juvenile_misdemeanors": datasets.Value("int64"), "number_of_other_juvenile_offenses": datasets.Value("int64"), "days_before_screening_arrest": datasets.Value("int64"), "is_recidivous": datasets.Value("bool"), "days_in_custody": datasets.Value("int64"), "is_violent_recidivous": datasets.Value("bool"), "violence_decile_score": datasets.Value("int64"), "two_year_recidivous": datasets.Value("int64"), "number_of_prior_offenses": datasets.Value("int64"), "race": datasets.ClassLabel(num_classes=6, names=("Caucasian", "African-American", "Hispanic", "Asian", "Other", "Native American")), } } features_per_config = {k: datasets.Features(features_types_per_config[k]) for k in features_types_per_config} class CompasConfig(datasets.BuilderConfig): def __init__(self, **kwargs): super(CompasConfig, self).__init__(version=VERSION, **kwargs) self.features = features_per_config[kwargs["name"]] class Compas(datasets.GeneratorBasedBuilder): # dataset versions DEFAULT_CONFIG = "two-years-recidividity" BUILDER_CONFIGS = [ CompasConfig(name="race", description="Multiclass classification, predict `race` out of other features."), CompasConfig(name="two-years-recidividity", description="Compas binary classification for two-year recidividity."), CompasConfig(name="two-years-recidividity-no-race", description="Compas binary classification for two-year recidividity. Race excluded from features."), CompasConfig(name="priors-prediction", description="Compas regression task for estimating number of prior offenses of defendant."), CompasConfig(name="priors-prediction-no-race", description="Compas regression task for estimating number of prior offenses of defendant. Race excluded from features."), CompasConfig(name="encoding", description="Encoding dictionaries for discrete labels."), ] 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.encoding_dics() 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 preprocess(self, data: pandas.DataFrame, config: str = "income") -> pandas.DataFrame: data.drop("id", axis="columns", inplace=True) data.drop("name", axis="columns", inplace=True) data.drop("first", axis="columns", inplace=True) data.drop("last", axis="columns", inplace=True) data.drop("dob", axis="columns", inplace=True) data.drop("age_cat", axis="columns", inplace=True) data.drop("c_offense_date", axis="columns", inplace=True) data.drop("c_jail_in", axis="columns", inplace=True) data.drop("c_jail_out", axis="columns", inplace=True) data.drop("c_arrest_date", axis="columns", inplace=True) data.drop("c_charge_degree", axis="columns", inplace=True) data.drop("c_charge_desc", axis="columns", inplace=True) data.drop("r_case_number", axis="columns", inplace=True) data.drop("r_charge_degree", axis="columns", inplace=True) data.drop("r_offense_date", axis="columns", inplace=True) data.drop("r_charge_desc", axis="columns", inplace=True) data.drop("violent_recid", axis="columns", inplace=True) data.drop("vr_case_number", axis="columns", inplace=True) data.drop("vr_charge_degree", axis="columns", inplace=True) data.drop("vr_offense_date", axis="columns", inplace=True) data.drop("vr_charge_desc", axis="columns", inplace=True) data.drop("type_of_assessment", axis="columns", inplace=True) data.drop("score_text", axis="columns", inplace=True) data.drop("v_score_text", axis="columns", inplace=True) data.drop("v_screening_date", axis="columns", inplace=True) data.drop("screening_date", axis="columns", inplace=True) data.drop("start", axis="columns", inplace=True) data.drop("end", axis="columns", inplace=True) data.drop("event", axis="columns", inplace=True) data.drop("two_year_recid.1", axis="columns", inplace=True) data.drop("r_jail_in", axis="columns", inplace=True) data.drop("r_jail_out", axis="columns", inplace=True) data.drop("v_type_of_assessment", axis="columns", inplace=True) data.drop("compas_screening_date", axis="columns", inplace=True) data.drop("decile_score.1", axis="columns", inplace=True) data.drop("priors_count.1", axis="columns", inplace=True) data.drop("c_case_number", axis="columns", inplace=True) data.drop("c_days_from_compas", axis="columns", inplace=True) data.drop("r_days_from_arrest", axis="columns", inplace=True) # handle nan values data.loc[data.days_b_screening_arrest.isna(), "days_b_screening_arrest"] = -1 data.loc[:, "days_b_screening_arrest"] = data.days_b_screening_arrest.astype(int) # transform columns into intervals data = data[(~data.in_custody.isna()) & (~data.out_custody.isna())] in_dates = data.in_custody.apply(datetime.date.fromisoformat) out_dates = data.out_custody.apply(datetime.date.fromisoformat) days_in_custody = [delta.days for delta in out_dates - in_dates] data.loc[:, "days_in_custody"] = days_in_custody data.drop("in_custody", axis="columns", inplace=True) data.drop("out_custody", axis="columns", inplace=True) data = data[["sex", "age", "race", "juv_fel_count", "decile_score", "juv_misd_count", "juv_other_count", "priors_count", "days_b_screening_arrest", "is_recid", "days_in_custody", "is_violent_recid", "v_decile_score", "two_year_recid"]] data.columns = _BASE_FEATURE_NAMES for feature in _ENCODING_DICS: if feature == "race": if config != "race": continue encoding_function = partial(self.encode, feature) data.loc[:, feature] = data[feature].apply(encoding_function) data.loc[:, "is_recidivous"] = data["is_recidivous"].apply(bool) data.loc[:, "is_violent_recidivous"] = data["is_violent_recidivous"].apply(bool) data = data.astype({"is_recidivous": "bool", "is_violent_recidivous": "bool"}) return data[list(features_types_per_config[config].keys())] def encode(self, feature, value): if feature in _ENCODING_DICS: return _ENCODING_DICS[feature][value] raise ValueError(f"Unknown feature: {feature}") def encoding_dics(self): data = [pandas.DataFrame([(feature, original, encoded) for original, encoded in d.items()]) for feature, d in _ENCODING_DICS.items()] data = pandas.concat(data, axis="rows").reset_index() data.drop("index", axis="columns", inplace=True) data.columns = ["feature", "original_value", "encoded_value"] return data