make_dataset.py 5.96 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
import config as cfg
from tools import file_reader, file_writer, feature_maker
from tools import preprocessor, neural_embedder
from utility import embedder
import pandas as pd
import numpy as np
from pathlib import Path
from sklearn.decomposition import PCA

11
CASES = ["Complete", "Success", "Fall"]
12
USE_ATS_NAMES = True
13
14
15
16

def main():
    cl = file_reader.read_csv(cfg.INTERIM_DATA_DIR, 'cl.csv',
                              converters={'CitizenId': str, 'Cluster': int})
Christian Marius Lillelund's avatar
Christian Marius Lillelund committed
17
    df = file_reader.read_csv(cfg.INTERIM_DATA_DIR, 'screenings.csv',
18
                              converters={'CitizenId': str})
19
20
21
22
    fd = file_reader.read_pickle(cfg.INTERIM_DATA_DIR, 'fd.pkl')
    
    longterm_fall_df = make_longterm_fall(df, fd)
    file_writer.write_csv(longterm_fall_df, cfg.PROCESSED_DATA_DIR, f'longterm_fall.csv')
23
24
25
26
27
28
29
30
31
32
33
    
    for case in CASES:
        df_full = make_dataset_full(cl, df, case)
        file_writer.write_csv(df_full, cfg.PROCESSED_DATA_DIR, f'{case.lower()}.csv')

        df_count = make_dataset_count(case)
        file_writer.write_csv(df_count, cfg.PROCESSED_DATA_DIR, f'{case.lower()}_count.csv')
        
        df_emb = make_dataset_emb(case)
        file_writer.write_csv(df_emb, cfg.PROCESSED_DATA_DIR, f'{case.lower()}_emb.csv')

34
35
36
37
38
39
40
41
42
def make_longterm_fall(df, fd):
    fd = fd.drop_duplicates(["CitizenId", "Date"])
    df = preprocessor.split_cat_columns(df, col='Ats', tag='Ats',
                                    resolution=cfg.ATS_RESOLUTION)
    
    df = feature_maker.make_longterm_fall_feature(df, fd)
    
    return df

43
def make_dataset_full(cl: pd.DataFrame, df: pd.DataFrame, case: str):
44
    df['Cluster'] = cl['Cluster']
45
46
    df = preprocessor.split_cat_columns(df, col='Ats', tag='Ats',
                                        resolution=cfg.ATS_RESOLUTION)
47
48
49

    if case == "Complete":
        df = feature_maker.make_complete_feature(df)
50
51
    elif case == "Success":
        df = feature_maker.make_success_feature(df)
52
53
54
55
56
57
    else:
        df = feature_maker.make_fall_feature(df)

    ats_cols = df.filter(regex='Ats', axis=1)
    general_cols = df[['Gender', 'BirthYear', 'Cluster', 'LoanPeriod']]
    df = pd.concat([general_cols, ats_cols, df[[case]]], axis=1)
58
    
59
60
61
    if USE_ATS_NAMES:
        df = preprocessor.replace_ats_values(df)
    
62
63
64
    return df

def make_dataset_count(case: str):
65
    ats = {str(i)+'Ats':str for i in range(1, cfg.ATS_RESOLUTION+1)}
66
67
68
69
    df = file_reader.read_csv(cfg.PROCESSED_DATA_DIR,
                              f'{case.lower()}.csv',
                              converters=ats)
    
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    if USE_ATS_NAMES:
        cols_ats = [str(i)+'Ats' for i in range(1, cfg.ATS_RESOLUTION+1)]
        unique_ats = [df[f'{i}Ats'].unique() for i in range(1, cfg.ATS_RESOLUTION+1)]
        unique_ats = list(set(np.concatenate(unique_ats)))
        df_ats = preprocessor.extract_cat_count(df, unique_ats, cols_ats, '')
        df = df.drop(cols_ats, axis=1)
        df = pd.concat([df.drop(case, axis=1), df_ats, df[[case]]], axis=1)
        df = df.drop('0', axis=1)
    else:
        num_cols = embedder.get_numerical_cols(df, case)
        cols_ats = [str(i)+'Ats' for i in range(1, cfg.ATS_RESOLUTION+1)]
        unique_ats = [df[f'{i}Ats'].unique() for i in range(1, cfg.ATS_RESOLUTION+1)]
        unique_ats = list(set(np.concatenate(unique_ats)))
        df_ats = preprocessor.extract_cat_count(df, unique_ats, cols_ats, 'Ats_')
        df = pd.concat([df, df_ats], axis=1)
        ats_columns = ['Ats_' + ats for ats in unique_ats]
        df = df[num_cols + ats_columns + [case]]
        df = df.drop(['Ats_0'], axis=1)
88
89
90
    return df

def make_dataset_emb(case: str):
91
    ats = {str(i)+'Ats':str for i in range(1, cfg.ATS_RESOLUTION+1)}
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    df = file_reader.read_csv(cfg.PROCESSED_DATA_DIR,
                              f'{case.lower()}.csv',
                              converters=ats)

    emb_cols = df.filter(regex='((\d+)[Ats])\w+', axis=1)
    n_numerical_cols = df.shape[1] - emb_cols.shape[1] - 1
    
    df_to_enc = df.iloc[:,n_numerical_cols:]
    target_name = case
    train_ratio = 0.9
    
    X_train, X_val, y_train, y_val, labels = preprocessor.prepare_data_for_embedder(df_to_enc,
                                                                                    target_name,
                                                                                    train_ratio)
    if case == "Complete":
        artifacts_path = cfg.COMPLETE_EMB_DIR
        epochs = 5
109
110
111
    elif case == "Success":
        artifacts_path = cfg.SUCCESS_EMB_DIR
        epochs = 5
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
    else:
        artifacts_path = cfg.FALL_EMB_DIR
        epochs = 20

    params = {"df": df_to_enc,
            "target_name": target_name,
            "train_ratio": train_ratio,
            "network_layers": ([128]),
            "epochs": epochs,
            "batch_size": 128,
            "verbose": False,
            "artifacts_path": artifacts_path}

    network = neural_embedder.NeuralEmbedder(**params)
    network.fit(X_train, y_train, X_val, y_val)
    network.save_model()
    embedded_weights = network.get_embedded_weights()
    network.save_weights(embedded_weights)
    network.save_labels(labels)
    network.make_visualizations_from_network(extension='png')
    
    emb_cols = df.filter(regex='((\d+)[Ats])\w+', axis=1)
    n_numerical_cols = df.shape[1] - emb_cols.shape[1] - 1
    
    embedded_df = df.iloc[:, n_numerical_cols:df.shape[1]-1]
    for index in range(embedded_df.shape[1]):
        column = embedded_df.columns[index]
        labels_column = labels[index]
        embeddings_column = embedded_weights[index]
        pca = PCA(n_components=1)
        Y = pca.fit_transform(embeddings_column)
        y_array = np.concatenate(Y)
        mapping = dict(zip(labels_column.classes_, y_array))
145
146
147
        file_writer.write_mapping(mapping,
                                  Path.joinpath(cfg.PROCESSED_DATA_DIR, 'embeddings'),
                                  f'{case.lower()}_{column}.csv')
148
149
150
151
152
153
        df[column] = df[column].replace(to_replace=mapping)

    return df

if __name__ == "__main__":
    main()