bank / bank.py
mstz's picture
Upload bank.py
db4e3d0
raw
history blame
5.63 kB
"""Bank Dataset"""
from typing import List
from functools import partial
import datasets
import pandas
VERSION = datasets.Version("1.0.0")
_ORIGINAL_FEATURE_NAMES = [
"age",
"job",
"marital",
"education",
"default",
"balance",
"housing",
"loan",
"contact",
"day",
"month",
"duration",
"campaign",
"pdays",
"previous",
"poutcome",
"y"
]
_BASE_FEATURE_NAMES = [
"age",
"job",
"marital_status",
"education_level",
"has_defaulted",
"account_balance",
"has_housing_loan",
"has_personal_loan",
"month_of_last_contact",
"number_of_calls_in_ad_campaign",
"days_since_last_contact_of_previous_campaign",
"number_of_calls_before_this_campaign",
"successful_subscription"
]
_ENCODING_DICS = {
"education_level": {
"unknown": 0,
"primary": 1,
"secondary": 2,
"tertiary": 3
},
"has_personal_loan": {
"no": 0,
"yes": 1
},
"has_housing_loan": {
"no": 0,
"yes": 1
},
"has_defaulted": {
"no": 0,
"yes": 1
},
"successful_subscription": {
"no": 0,
"yes": 1
}
}
DESCRIPTION = "Bank dataset for subscription prediction."
_HOMEPAGE = "https://archive.ics.uci.edu/ml/datasets/bank+marketing"
_URLS = ("https://huggingface.co./datasets/mstz/bank/raw/main/bank-full.csv")
_CITATION = """"""
# Dataset info
urls_per_split = {
"train": "https://huggingface.co./datasets/mstz/bank/raw/main/bank-full.csv",
}
features_types_per_config = {
"encoding": {
"feature": datasets.Value("string"),
"original_value": datasets.Value("string"),
"encoded_value": datasets.Value("int8"),
},
"subscription": {
"age": datasets.Value("int64"),
"job": datasets.Value("string"),
"marital_status": datasets.Value("string"),
"education_level": datasets.Value("int8"),
"has_defaulted": datasets.Value("int8"),
"account_balance": datasets.Value("int64"),
"has_housing_loan": datasets.Value("int8"),
"has_personal_loan": datasets.Value("int8"),
"month_of_last_contact": datasets.Value("string"),
"number_of_calls_in_ad_campaign": datasets.Value("string"),
"days_since_last_contact_of_previous_campaign": datasets.Value("int16"),
"number_of_calls_before_this_campaign": datasets.Value("int16"),
"successful_subscription": 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 BankConfig(datasets.BuilderConfig):
def __init__(self, **kwargs):
super(BankConfig, self).__init__(version=VERSION, **kwargs)
self.features = features_per_config[kwargs["name"]]
class Bank(datasets.GeneratorBasedBuilder):
# dataset versions
DEFAULT_CONFIG = "subscription"
BUILDER_CONFIGS = [
BankConfig(name="encoding",
description="Encoding dictionaries for discrete features."),
BankConfig(name="subscription",
description="Bank binary classification for client subscription."),
]
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"]}),
]
def _generate_examples(self, filepath: str):
if self.config.name == "encoding":
data = self.encoding_dictionaries()
else:
data = pandas.read_csv(filepath, sep=";")
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 = "subscription") -> pandas.DataFrame:
if config == "subscription":
data.drop("day", axis="columns", inplace=True)
data.drop("contact", axis="columns", inplace=True)
data.drop("duration", axis="columns", inplace=True)
data.drop("poutcome", axis="columns", inplace=True)
data.columns = _BASE_FEATURE_NAMES
for feature in _ENCODING_DICS:
encoding_function = partial(self.encode, feature)
data.loc[:, feature] = data[feature].apply(encoding_function)
return data
else:
raise ValueError(f"Unknown config: {config}")
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