Preprocess data¶
auxiliary_data ¶
surname_origin_bert ¶
surname_origin_bert(df, surname_col)
THIS IS WORK IN PROGRESS!!! Surname classification that uses adjusted script scripts/surname_classification_with_bert.py) from: https://www.kaggle.com/code/yonatankpl/surname-classification-with-bert to train a bert model for surname classification
additional data from: https://github.com/greenelab/wiki-nationality-estimate/tree/master
and possibly data from: https://github.com/philipperemy/name-dataset?tab=readme-ov-file#full-dataset
Parameters:
-
df
(
pd.DataFrame
) –input dataset
-
surname_col
(
str
) –column name with surnames
Source code in churn_pred/preprocessing/auxiliary_data.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
surname_origin ¶
surname_origin(df, surname_col)
Surname classification that uses db of names leaked from FB, see: https://github.com/philipperemy/name-dataset
Parameters:
-
df
(
pd.DataFrame
) –input dataset
-
surname_col
(
str
) –column name with surnames
Source code in churn_pred/preprocessing/auxiliary_data.py
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 |
|
hemisphere ¶
hemisphere(df, cc_col, loc_db_df=None, city_col=None)
Returns string pd.Series identifing hemisphere: "northern" or "southern".
Parameters:
-
df
(
pd.DataFrame
) –input dataframe
-
city_col
(
str
) –city name column
-
cc_col
(
str
) –country code column
-
loc_db_df
(
pd.DataFrame
) –pandas dataframe with previously saved locations
Source code in churn_pred/preprocessing/auxiliary_data.py
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 |
|
age_categories ¶
age_categories(df, age_col)
Returns string pd.DataFrame identifing different age classification categories according to the age: * working_class (https://ourworldindata.org/age-structure) * children_and_adolescents: <0, 15) * working_age: <15, 65) * elderly: <65, inf) * stage_of_life (https://integrishealth.org/resources/on-your-health/2015/october/stages-of-life-health-for-every-age) * infant: <0, 2) * toddler: <2, 5) * child: <5, 13) * teen: <13, 20) * adult: <20, 40) * middle_age_adult: <40, 60) * senior_adult: <60, inf) * generation (https://www.beresfordresearch.com/age-range-by-generation/) * gen_z: <12, 28) * millennials: <28, 44) * gen_x: <44, 60) * boomers_2: <60, 70) * boomers_1: <70, 79) * post_war: <79, 97) * ww2: <97, 102) * vampire: <102, inf)
Parameters:
-
df
(
pd.DataFrame
) –input dataset
-
age_col
(
str
) –age column
Source code in churn_pred/preprocessing/auxiliary_data.py
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 |
|
big_mac_index ¶
big_mac_index(df, country_name_col)
Returns dataframe with Big Max Index corresponding to country codes. Downloaded on 26/4/2024.
Note
Unfortunatelly Spain, France, Germany (unique companies in the dataset) are not included, other index to explore: https://en.wikipedia.org/wiki/Big_Mac_Index
Based on
Downloaded from
Parameters:
-
df
(
pd.DataFrame
) –input dataset
-
country_name_col
(
str
) –column name with country names
Source code in churn_pred/preprocessing/auxiliary_data.py
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
|
gdppc ¶
gdppc(df, country_name_col)
Returns dataframe with Gross Domestic Product Per Capita corresponding to country codes. Uses information from worldbank API downloaded on 26/4/2024. Last file update: 3/28/2024. Posprocessed file has initial 3 lines removed for easier processing using pandas df.
Downloaded from
Main file before preprocessing
'data/gdpp/API_NY.GDP.PCAP.PP.CD_DS2_en_csv_v2_213153.csv'
Other included files
'data/gdpp/Metadata_Country_API_NY.GDP.PCAP.PP.CD_DS2_en_csv_v2_213153.csv' 'data/gdpp/Metadata_Indicator_API_NY.GDP.PCAP.PP.CD_DS2_en_csv_v2_213153.csv'
Parameters:
-
df
(
pd.DataFrame
) –input dataset
-
country_name_col
(
str
) –column name with country names
Source code in churn_pred/preprocessing/auxiliary_data.py
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 |
|
get_iso_a3 ¶
get_iso_a3(df, country_name_col)
Returns pd.Series with mapped country names to iso_a3.
Parameters:
-
df
(
pd.Series
) –input country name pandas series
Source code in churn_pred/preprocessing/auxiliary_data.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 |
|
get_country_name ¶
get_country_name(df, country_name_col)
Returns pd.Series with mapped country iso_a2 to names.
Parameters:
-
df
(
pd.Series
) –input country name pandas series
Source code in churn_pred/preprocessing/auxiliary_data.py
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 |
|
get_country_region_subregion ¶
get_country_region_subregion(df, country_name_col)
Returns pd.Series with mapped country iso_a2 to names.
Parameters:
-
df
(
pd.Series
) –input country name pandas series
Source code in churn_pred/preprocessing/auxiliary_data.py
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
|
label_encoder ¶
LabelEncoder ¶
LabelEncoder(columns_to_encode=None)
Bases: object
Label Encode categorical values for multiple columns at once
NOTE: Shamlessly copied from https://github.com/jrzaurin/pytorch-widedeep
NOTE:
LabelEncoder reserves 0 for unseen
new categories. This is convenient
when defining the embedding layers, since we can just set padding idx to 0.
Parameters:
-
columns_to_encode
(
list, Optional, default = None
) –List of strings containing the names of the columns to encode. If
None
all columns of typeobject
in the dataframe will be label encoded.
Attributes:
-
encoding_dict
(
Dict
) –Dictionary containing the encoding mappings in the format, e.g. :
{'colname1': {'cat1': 1, 'cat2': 2, ...}, 'colname2': {'cat1': 1, 'cat2': 2, ...}, ...}
# noqa -
inverse_encoding_dict(Dict)
(
Dict
) –Dictionary containing the inverse encoding mappings in the format, e.g. :
{'colname1': {1: 'cat1', 2: 'cat2', ...}, 'colname2': {1: 'cat1', 2: 'cat2', ...}, ...}
# noqa
Source code in churn_pred/preprocessing/label_encoder.py
29 30 31 32 33 |
|
fit ¶
fit(df)
Creates encoding attributes
Returns:
-
LabelEncoder(
LabelEncoder
) –LabelEncoder
fitted object
Source code in churn_pred/preprocessing/label_encoder.py
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 |
|
transform ¶
transform(df)
Label Encoded the categories in columns_to_encode
Returns:
-
pd.DataFrame
–pd.DataFrame: label-encoded dataframe
Source code in churn_pred/preprocessing/label_encoder.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
|
fit_transform ¶
fit_transform(df)
Combines fit
and transform
Returns:
-
pd.DataFrame
–pd.DataFrame: label-encoded dataframe
Examples:
>>> import pandas as pd
>>> from churn_pred.preprocessing.label_encoder import LabelEncoder
>>> df = pd.DataFrame({'col1': [1,2,3], 'col2': ['me', 'you', 'him']})
>>> columns_to_encode = ['col2']
>>> encoder = LabelEncoder(columns_to_encode)
>>> encoder.fit_transform(df)
col1 col2
0 1 1
1 2 2
2 3 3
>>> encoder.encoding_dict
{'col2': {'me': 1, 'you': 2, 'him': 3}}
Source code in churn_pred/preprocessing/label_encoder.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
|
inverse_transform ¶
inverse_transform(df)
Returns the original categories
Returns:
-
pd.DataFrame
–pd.DataFrame: label-encoded dataframe
Examples:
>>> import pandas as pd
>>> from churn_pred.preprocessing.label_encoder import LabelEncoder
>>> df = pd.DataFrame({'col1': [1,2,3], 'col2': ['me', 'you', 'him']})
>>> columns_to_encode = ['col2']
>>> encoder = LabelEncoder(columns_to_encode)
>>> df_enc = encoder.fit_transform(df)
>>> encoder.inverse_transform(df_enc)
col1 col2
0 1 me
1 2 you
2 3 him
Source code in churn_pred/preprocessing/label_encoder.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
|
preprocess_data ¶
drop_high_nan_cols ¶
drop_high_nan_cols(df, threshold=0.8, verbose=False)
Returns dataframe without columns that have ratio of missingness above threshold.
Parameters:
-
df
(
pd.DataFrame
) –input dataframe
-
threshold
(
float = 0.8
) –ratio of missingness applied per column
-
verbose
(
bool
) –whether the output should be verbose
Source code in churn_pred/preprocessing/preprocess_data.py
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 |
|
drop_constant_cols ¶
drop_constant_cols(df, verbose=False)
Returns dataframe without constant columns, i.e. those with just 1 unique value for all rows.
Source code in churn_pred/preprocessing/preprocess_data.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
|
drop_high_uq_cat_cols ¶
drop_high_uq_cat_cols(
df, cat_cols, uq_val_count, verbose=False
)
Returns dataframe without categorical columns that have too many unique values
Parameters:
-
df
(
pd.DataFrame
) –input dataframe
-
cat_cols
(
list
) –list of categorical columns
-
uq_val_count
(
int
) –unique value count
-
verbose
(
bool
) –whether the output should be verbose
Source code in churn_pred/preprocessing/preprocess_data.py
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 |
|
drop_highly_correlated_columns ¶
drop_highly_correlated_columns(
df, cont_cols, crosscorr_val=0.95, verbose=False
)
Returns dataframe without highly correlated columns, cross correlation is evaluated with crosscorr_val.
Parameters:
-
df
(
pd.DataFrame
) –input dataframe
-
cont_cols
(
list
) –list of columns to evaluate correlation for
-
crosscorr_val
(
float = 0.95
) –threshold value of correlation
-
verbose
(
bool
) –whether the output should be verbose
Source code in churn_pred/preprocessing/preprocess_data.py
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 |
|
nan_with_unknown_imputer ¶
nan_with_unknown_imputer(
df, columns, fill_token="unknown", verbose=False
)
Fills NAs with surrogate string, 'unknown' is default value used, it can be customized.
Parameters:
-
df
(
pd.DataFrame
) –input dataframe
-
columns
(
List[str]
) –ist of columns that will be filled
-
fill_token
(
str = "unknown"
) –string used to replace NAs
-
verbose
(
bool
) –whether the output should be verbose
Source code in churn_pred/preprocessing/preprocess_data.py
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 |
|
nan_with_number_imputer ¶
nan_with_number_imputer(
df, columns, fill_number=-1.0, verbose=False
)
Fills NAs with surrogate float, -1 is default value used, it can be customized.
Parameters:
-
df
(
pd.DataFrame
) –input dataframe
-
columns
(
List[str]
) –list of columns that will be filled
-
fill_number
(
float = -1
) –number used to replace NAs. Defaults to
-
verbose
(
bool
) –whether the output should be verbose
Source code in churn_pred/preprocessing/preprocess_data.py
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 |
|
nuq_in_list_col ¶
nuq_in_list_col(dfs)
Returns pd.Series with the number of unique values in the lists.
Parameters:
-
dfs
(
pd.Series
) –input pandas series containing string list values
Source code in churn_pred/preprocessing/preprocess_data.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
|
most_frequent_in_list_col ¶
most_frequent_in_list_col(dfs)
Returns pd.Series with the most frequent values in the lists.
Parameters:
-
dfs
(
pd.Series
) –input pandas series containing string list values
Source code in churn_pred/preprocessing/preprocess_data.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
|
replace_rare_categories_with_str_other ¶
replace_rare_categories_with_str_other(
df,
categorical_cols,
quantile=0.05,
surrogate_value="other",
verbose=False,
)
Replaces rare category value with surrogate string.
Parameters:
-
df
(
pd.DataFrame
) –input dataframe
-
categorical_cols
(
List[str]
) –list of columns in dataframe to process.
-
quantile
(
float = 0.05
) –determines what values are considered as rare
-
surrogate_value
(
str = "other"
) –string used to replace rare values
Returns:
-
Tuple[pd.DataFrame, Dict]
–Tuple[pd.DataFrame, Dict]: New dataframe and a dict. with mapping between orig. and surrogate values.
Source code in churn_pred/preprocessing/preprocess_data.py
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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 |
|
preprocess_text ¶
language_detection ¶
language_detection(df, text_col, model_type='fasttext')
Source code in churn_pred/preprocessing/preprocess_text.py
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 |
|
text_cleaning ¶
text_cleaning(df, text_col)
Returns dataframe with preprocessed/cleaned text column. Spacy-cleaner that uses spacy functionalities. https://spacy.io/universe/project/spacy-cleaner
Note
The spacy-cleaner library does not do much. Future task - develop own cleaner
Parameters:
-
df
(
pd.DataFrame
) –input dataset
-
text_col
(
str
) –column name with text
Source code in churn_pred/preprocessing/preprocess_text.py
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 |
|
sentiment_analysis ¶
sentiment_analysis(df, text_col, sentiment_depth=3)
Returns dataframe with new column that analysis sentintent in the text_col.
initial idea: Inspired by https://www.nature.com/articles/s41598-024-60210-7 I also used the 3 most popular models with voting: 1. cardiffnlp/twitter-roberta-base-sentiment-latest 2. nlptown/bert-base-multilingual-uncased-sentiment 3. mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis 4. lxyuan/distilbert-base-multilingual-cased-sentiments-student 5. finiteautomata/bertweet-base-sentiment-analysis
issues: 1. 3(pos, neutral, neg) vs 5(1-5 stars) sentiments; models 1,3 vs 2 2. maximum sequence length models 4-5
final idea: Either 3 sentimnets(model 1) or 5 stars (model 2)
Parameters:
-
df
(
pd.DataFrame
) –input dataset
-
text_col
(
str
) –column name with text
-
sentiment_depth
(
[3, 5]
) –depth of sentiment analysis
Source code in churn_pred/preprocessing/preprocess_text.py
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 |
|
preprocess ¶
PreprocessData ¶
PreprocessData(
target_col, id_cols, cat_cols=None, cont_cols=None
)
Object to preprocess the dataset.
Parameters:
-
target_col
(
str
) –target column name
-
id_cols
(
List[str]
) –id columns
-
cat_cols
(
Optional[List[str]]
) –list of categorical column names
-
cont_cols
(
Optional[List[str]]
) –list of continuous column names
Source code in churn_pred/preprocessing/preprocess.py
28 29 30 31 32 33 34 35 36 37 38 39 40 |
|
fit_transform ¶
fit_transform(df)
Fit peprocessor and transform dataset in training step.
Source code in churn_pred/preprocessing/preprocess.py
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 |
|
transform ¶
transform(df)
Transform dataset in inference step.
Source code in churn_pred/preprocessing/preprocess.py
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 |
|
fit ¶
fit(df)
Just to keep familiar naming convention with sklearn.
Source code in churn_pred/preprocessing/preprocess.py
134 135 136 |
|
scaler ¶
scaler_mapper ¶
scaler_mapper(
cont_cols, cat_cols, id_cols, scaler_mapper_def=None
)
Function that maps scaler functions to appropriate columns.
By default does not assign any scaler to continuous, categorical or identifier columns. The scalers must be set in scaler_mapper_def. Use sklearn scalers. Only columns defined in mapper object will be present in the transformed dataset.
Parameters:
-
cont_cols
(
list
) –list of continuous feature columns in the dataset
-
cat_cols
(
list
) –list of categorical feature columns in the dataset
-
id_cols
(
list
) –identifier columns
-
scaler_mapper_def
(
dict
) –optional dictionary that contains keys ['cont_cols', 'cat_cols', 'id_cols'] with their corresponding scalers (defined by names, not instantiated) from sklearn library
Returns:
-
scaler(
DataFrameMapper
) –scaler object mapping sklearn scalers to columns in pandas dataframe
Source code in churn_pred/preprocessing/scaler.py
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 |
|