File size: 9,632 Bytes
1a21c3b
e89b705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344b4bc
 
 
 
 
 
 
 
 
 
 
 
bd37b96
344b4bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1132072
344b4bc
 
 
e89b705
 
 
 
 
 
 
e87164a
e89b705
 
 
 
 
 
 
 
 
918a573
e89b705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
918a573
e89b705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85643b2
e89b705
d6904d9
e89b705
 
 
 
 
 
 
 
 
 
 
 
 
0aed351
 
 
 
85643b2
 
 
 
 
 
aa8ed81
c80c0eb
f975d90
0bf0679
 
 
 
2d1c894
e89b705
 
3982980
16a6e7f
d04c4b5
8ec8b31
 
 
 
 
 
 
 
 
1132072
107518d
e89b705
0aed351
 
 
 
125418d
88956b9
0b95dbe
e89b705
 
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
"""NBFI"""

from typing import List
from functools import partial

import datasets

import pandas


VERSION = datasets.Version("1.0.0")
_ORIGINAL_FEATURE_NAMES = [
    "ID",
    "Client_Income",
    "Car_Owned",
    "Bike_Owned",
    "Active_Loan",
    "House_Own",
    "Child_Count",
    "Credit_Amount",
    "Loan_Annuity",
    "Accompany_Client",
    "Client_Income_Type",
    "Client_Education",
    "Client_Marital_Status",
    "Client_Gender",
    "Loan_Contract_Type",
    "Client_Housing_Type",
    "Population_Region_Relative",
    "Age_Days",
    "Employed_Days",
    "Registration_Days",
    "ID_Days",
    "Own_House_Age",
    "Mobile_Tag",
    "Homephone_Tag",
    "Workphone_Working",
    "Client_Occupation",
    "Client_Family_Members",
    "Cleint_City_Rating",
    "Application_Process_Day",
    "Application_Process_Hour",
    "Client_Permanent_Match_Tag",
    "Client_Contact_Work_Tag",
    "Type_Organization",
    "Score_Source_1",
    "Score_Source_2",
    "Score_Source_3",
    "Social_Circle_Default",
    "Phone_Change",
    "Credit_Bureau",
    "Default"
]
_BASE_FEATURE_NAMES = [
    "income",
    "owns_a_car",
    "owns_a_bike",
    "has_an_active_loan",
    "owns_a_house",
    "nr_children",
    "credit",
    "loan_annuity",
    "accompanied_by",
    "income_type",
    "education_level",
    "marital_status",
    "is_male",
    "type_of_contract",
    "type_of_housing",
    "residence_density",
    "age_in_days",
    "consecutive_days_of_employment",
    "nr_days_since_last_registration_change",
    "nr_days_since_last_document_change",
    "has_provided_a_mobile_number",
    "has_provided_a_home_number",
    "was_reachable_at_work",
    "job",
    "nr_family_members",
    "city_rating",
    "weekday_of_application",
    "hour_of_application",
    "same_residence_and_home",
    "same_work_and_home",
    "score_1",
    "score_2",
    "score_3",
    "nr_defaults_in_social_circle",
    "inquiries_in_last_year",
    "has_defaulted"
]
features_types_per_config = {
    "default": {
        "income": datasets.Value("float32"),
        "owns_a_car": datasets.Value("bool"),
        "owns_a_bike": datasets.Value("bool"),
        "has_an_active_loan": datasets.Value("bool"),
        "owns_a_house": datasets.Value("bool"),
        "nr_children": datasets.Value("int8"),
        "credit": datasets.Value("float32"),
        "loan_annuity": datasets.Value("float32"),
        "accompanied_by": datasets.Value("string"),
        "income_type": datasets.Value("string"),
        "education_level": datasets.Value("float32"),
        "marital_status": datasets.Value("string"),
        "is_male": datasets.Value("bool"),
        "type_of_contract": datasets.Value("string"),
        "type_of_housing": datasets.Value("string"),
        "residence_density": datasets.Value("float32"),
        "age_in_days": datasets.Value("int32"),
        "consecutive_days_of_employment": datasets.Value("int16"),
        "nr_days_since_last_registration_change": datasets.Value("int32"),
        "nr_days_since_last_document_change": datasets.Value("int32"),
        "has_provided_a_mobile_number": datasets.Value("bool"),
        "has_provided_a_home_number": datasets.Value("bool"),
        "was_reachable_at_work": datasets.Value("bool"),
        "job": datasets.Value("string"),
        "nr_family_members": datasets.Value("int8"),
        "city_rating": datasets.Value("int8"),
        "weekday_of_application": datasets.Value("int8"),
        "hour_of_application": datasets.Value("float32"),
        "same_residence_and_home": datasets.Value("bool"),
        "same_work_and_home": datasets.Value("bool"),
        "score_1": datasets.Value("float32"),
        "score_2": datasets.Value("float32"),
        "score_3": datasets.Value("float32"),
        "nr_defaults_in_social_circle": datasets.Value("bool"),
        "inquiries_in_last_year": datasets.Value("float32"),
        "has_defaulted": datasets.ClassLabel(num_classes=2, names=("no", "yes"))
    }
}
_ENCODING_DICS = {}
_EDUCATION_ENCODING = {
    "Junior secondary": 0,
    "Secondary": 1,
    "Graduation dropout": 2,
    "Graduation": 2,
    "Post Grad": 4
}    

DESCRIPTION = "NBFI dataset from default prediction."
_HOMEPAGE = "https://www.kaggle.com/datasets/meastanmay/nbfi-vehicle-loan-repayment-dataset"
_URLS = ("https://www.kaggle.com/datasets/meastanmay/nbfi-vehicle-loan-repayment-dataset")
_CITATION = """"""

# Dataset info
urls_per_split = {
    "train": "https://gist.githubusercontent.com/msetzu/6c83dc3b7092d428ae2f08dc91e1020c/raw/9fc3171b293d0dc29963357450308eb4c7e3a15b/Train_Dataset.csv"
}

features_per_config = {k: datasets.Features(features_types_per_config[k]) for k in features_types_per_config}


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


class NBFI(datasets.GeneratorBasedBuilder):
    # dataset versions
    DEFAULT_CONFIG = "default"
    BUILDER_CONFIGS = [
        NBFIConfig(name="default",
                    description="NBFI for default binary 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"]})
        ]
    
    def _generate_examples(self, filepath: str):
        if self.config.name == "default":
            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
        else:
            raise ValueError(f"Unknown config: {self.config.name}")



    def preprocess(self, data: pandas.DataFrame, config: str = DEFAULT_CONFIG) -> pandas.DataFrame:
        data.drop("ID", axis="columns", inplace=True)
        data.drop("Own_House_Age", axis="columns", inplace=True)
        data.drop("Type_Organization", axis="columns", inplace=True)
        data.drop("Phone_Change", axis="columns", inplace=True)

        data = data[~data.Client_Income.isna()]
        data = data[~data.Client_Education.isna()]
        data = data[~data.Child_Count.isna()]
        data = data[~data.Client_Marital_Status.isna()]
        data = data[~data.Client_Gender.isna()]
        data = data[~data.Loan_Contract_Type.isna()]
        data = data[~data.Client_Housing_Type.isna()]
        data = data[~data.Age_Days.isna()]
        data = data[~data.Employed_Days.isna()]
        data = data[~data.Registration_Days.isna()]
        data = data[~data.ID_Days.isna()]
        data = data[~data.Cleint_City_Rating.isna()]
        data = data[~data.Application_Process_Day.isna()]
        data = data[~data.Application_Process_Hour.isna()]
        data = data[~data.Client_Permanent_Match_Tag.isna()]
        data = data[~data.Client_Contact_Work_Tag.isna()]
        data = data[~data.Score_Source_1.isna()]
        data = data[~data.Score_Source_2.isna()]
        data = data[~data.Score_Source_3.isna()]
        data = data[~data.Credit_Bureau.isna()]
        data = data[~data.Credit_Amount.isna()]
        data = data[~data.Loan_Annuity.isna()]
        data = data[~data.Accompany_Client.isna()]
        data = data[~data.Client_Occupation.isna()]
        data = data[~data.Client_Family_Members.isna()]
        data = data[~data.Social_Circle_Default.isna()]
        data = data[~data.Population_Region_Relative.isin(("@", "#"))]
        data = data[~data.Population_Region_Relative.isna()]
        data = data[data.Loan_Annuity != "#VALUE!"]
        data = data[data.Age_Days != "x"]
        data = data[data.Employed_Days != "x"]
        data = data[data.Registration_Days != "x"]
        data = data[data.ID_Days != "x"]
        
        data.columns = _BASE_FEATURE_NAMES

        data["education_level"] = data["education_level"].apply(lambda x: _EDUCATION_ENCODING[x])
        data["is_male"] = data["is_male"].apply(lambda x: x == "M")
        data["owns_a_car"] = data["owns_a_car"].apply(bool)
        data["owns_a_bike"] = data["owns_a_bike"].apply(bool)
        data["has_an_active_loan"] = data["has_an_active_loan"].apply(bool)
        data["owns_a_house"] = data["owns_a_house"].apply(bool)
        data["is_male"] = data["is_male"].apply(bool)
        data["has_provided_a_mobile_number"] = data["has_provided_a_mobile_number"].apply(bool)
        data["has_provided_a_home_number"] = data["has_provided_a_home_number"].apply(bool)
        data["was_reachable_at_work"] = data["was_reachable_at_work"].apply(bool)
        data["same_residence_and_home"] = data["same_residence_and_home"].apply(bool)
        data["same_work_and_home"] = data["same_work_and_home"].apply(bool)
        data["nr_defaults_in_social_circle"] = data["same_work_and_home"].apply(bool)
        data["residence_density"] = data["residence_density"].apply(float)
        
        data = data.astype({
            "is_male": "bool",
            "nr_children": "int8"
        })
        


        return data[list(features_types_per_config[config].keys())]