File size: 8,903 Bytes
000de75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
"""Script that performs encoding of categorical features and imputation.

Performs encoding of categorical features, and imputation of missing values. After encoding
and imputation are performed, features are dropped. Two versions of the data is saved:
imputed and not imputed dataframes.
"""

import pandas as pd
import numpy as np
import os
import sys
import yaml
import json
import joblib
import encoding
import imputation


with open("./training/config.yaml", "r") as config:
    config = yaml.safe_load(config)

# Specify which model to generate features for
model_type = config["model_settings"]["model_type"]

# Setup log file
log = open("./training/logging/encode_and_impute_" + model_type + ".log", "w")
sys.stdout = log

# Dataset to process - set through config file
data_to_process = config["model_settings"]["data_to_process"]

# Load data
data = pd.read_pickle(
    os.path.join(
        config["outputs"]["processed_data_dir"],
        "{}_combined_{}.pkl".format(data_to_process, model_type),
    )
)

############################################################################
# Target encode categorical data
############################################################################

categorical_cols = [
    "LatestSymptomDiaryQ8",
    "LatestSymptomDiaryQ9",
    "LatestSymptomDiaryQ10",
    "DaysSinceLastExac",
    "AgeBinned",
    "Comorbidities",
    "FEV1PercentPredicted",
]

# Multiple types of nans present in data ('nan' and np.NaN). Convert all these to 'nan' for
# categorical columns
for categorical_col in categorical_cols:
    data[categorical_col] = data[categorical_col].replace(np.nan, "nan")

if data_to_process == "train":
    # Get target encodings for entire train set
    target_encodings = encoding.get_target_encodings(
        train_data=data,
        cols_to_encode=categorical_cols,
        target_col="ExacWithin3Months",
        smooth="auto",
    )
    train_encoded = encoding.apply_target_encodings(
        data=data,
        cols_to_encode=categorical_cols,
        encodings=target_encodings,
        drop_categorical_cols=False,
    )
    json.dump(
        target_encodings,
        open("./data/artifacts/target_encodings_" + model_type + ".json", "w"),
    )

    # K-fold target encode
    # Get info on which patients belong to which fold
    fold_patients = np.load(
        os.path.join(
            config["outputs"]["cohort_info_dir"],
            "fold_patients_{}.npy".format(model_type),
        ),
        allow_pickle=True,
    )
    train_encoded_cv, target_encodings = encoding.kfold_target_encode(
        df=data,
        fold_ids=fold_patients,
        cols_to_encode=categorical_cols,
        id_col="StudyId",
        target="ExacWithin3Months",
        smooth="auto",
        drop_categorical_cols=False,
    )

    # Drop categorical cols except for AgeBinned as it is needed in imputation step
    categorical_cols.remove("AgeBinned")
    train_encoded = train_encoded.drop(columns=categorical_cols)
    train_encoded_cv = train_encoded_cv.drop(columns=categorical_cols)

if (data_to_process == "test") | (data_to_process == "forward_val"):
    # Encode test set/forward val set based on entire train set
    target_encodings = json.load(
        open("./data/artifacts/target_encodings_" + model_type + ".json")
    )
    test_encoded = encoding.apply_target_encodings(
        data=data,
        cols_to_encode=categorical_cols,
        encodings=target_encodings,
        drop_categorical_cols=False,
    )

    # Drop categorical cols except for AgeBinned as it is needed in imputation step
    categorical_cols.remove("AgeBinned")
    test_encoded = test_encoded.drop(columns=categorical_cols)

############################################################################
# Impute missing data
############################################################################

cols_to_ignore = [
    "StudyId",
    "PatientId",
    "IndexDate",
    "ExacWithin3Months",
    "HospExacWithin3Months",
    "CommExacWithin3Months",
    "Age",
    "Sex_F",
    "SafeHavenID",
    "AgeBinned",
]

if data_to_process == "train":
    # Impute entire train set
    not_imputed_train = train_encoded.copy()
    cols_to_impute = train_encoded.drop(columns=cols_to_ignore).columns

    imputer = imputation.get_imputer(
        train_data=train_encoded,
        cols_to_impute=cols_to_impute,
        average_type="median",
        cols_to_groupby=["AgeBinned", "Sex_F"],
    )
    imputed_train = imputation.apply_imputer(
        data=train_encoded,
        cols_to_impute=cols_to_impute,
        imputer=imputer,
        cols_to_groupby=["AgeBinned", "Sex_F"],
    )
    joblib.dump(imputer, "./data/artifacts/imputer_" + model_type + ".pkl")

    # K-fold impute
    not_imputed_train_cv = train_encoded_cv.copy()
    imputed_train_cv = imputation.kfold_impute(
        df=train_encoded,
        fold_ids=fold_patients,
        cols_to_impute=cols_to_impute,
        average_type="median",
        cols_to_groupby=["AgeBinned", "Sex_F"],
        id_col="StudyId",
    )

    df_columns = imputed_train.columns.tolist()

if (data_to_process == "test") | (data_to_process == "forward_val"):
    not_imputed_test = test_encoded.copy()
    cols_to_impute = test_encoded.drop(columns=cols_to_ignore).columns

    # Impute test set/forward val set based on entire train set
    imputer = joblib.load("./data/artifacts/imputer_" + model_type + ".pkl")
    imputed_test = imputation.apply_imputer(
        data=test_encoded,
        cols_to_impute=cols_to_impute,
        imputer=imputer,
        cols_to_groupby=["AgeBinned", "Sex_F"],
    )

    df_columns = imputed_test.columns.tolist()

############################################################################
# Reduce feature space
############################################################################
cols_to_drop_startswith = (
    "DiffLatest",
    "Var",
    "LatestEQ5D",
    "TotalEngagement",
    "Age",
    "NumHosp",
    "Required",
    "LungFunction",
    "EngagementCAT",
    "LatestSymptomDiary",
    "LatestAlbumin",
    "LatestEosinophils",
    "LatestNeutrophils",
    "LatestWhite Blood Count",
)

additional_cols_to_drop = [
    "PatientId",
    "SafeHavenID",
    "Sex_F",
    "NumCommExacPrior6mo",
    "AsthmaOverlap",
    "TimeSinceLungFunc",
    "LatestNeutLymphRatio",
    "EngagementEQ5DTW1",
    "EngagementMRCTW1",
    "LatestMRCQ1",
    "WeekAvgCATQ1",
    "WeekAvgCATQ3",
    "WeekAvgCATQ4",
    "WeekAvgCATQ5",
    "WeekAvgCATQ6",
    "WeekAvgCATQ7",
    "WeekAvgCATQ8",
    "WeekAvgSymptomDiaryQ1",
    "WeekAvgSymptomDiaryQ3",
    "WeekAvgSymptomDiaryScore",
    "EngagementSymptomDiaryTW1",
    "ScaledSumSymptomDiaryQ3TW1",
    # "Comorbidities_te",
]

cols_to_drop = []
cols_to_drop.extend(
    [item for item in df_columns if item.startswith(cols_to_drop_startswith)]
)
cols_to_drop.extend(additional_cols_to_drop)

if data_to_process == "train":
    imputed_train = imputed_train.drop(columns=cols_to_drop)
    not_imputed_train = not_imputed_train.drop(columns=cols_to_drop)
    imputed_train_cv = imputed_train_cv.drop(columns=cols_to_drop)
    not_imputed_train_cv = not_imputed_train_cv.drop(columns=cols_to_drop)
if (data_to_process == "test") | (data_to_process == "forward_val"):
    imputed_test = imputed_test.drop(columns=cols_to_drop)
    not_imputed_test = not_imputed_test.drop(columns=cols_to_drop)

############################################################################
# Save data
############################################################################
os.makedirs(config["outputs"]["model_input_data_dir"], exist_ok=True)

if data_to_process == "train":
    imputed_train.to_pickle(
        os.path.join(
            config["outputs"]["model_input_data_dir"],
            "{}_imputed_{}.pkl".format(data_to_process, model_type),
        )
    )
    not_imputed_train.to_pickle(
        os.path.join(
            config["outputs"]["model_input_data_dir"],
            "{}_not_imputed_{}.pkl".format(data_to_process, model_type),
        )
    )
    imputed_train_cv.to_pickle(
        os.path.join(
            config["outputs"]["model_input_data_dir"],
            "{}_imputed_cv_{}.pkl".format(data_to_process, model_type),
        )
    )
    not_imputed_train_cv.to_pickle(
        os.path.join(
            config["outputs"]["model_input_data_dir"],
            "{}_not_imputed_cv_{}.pkl".format(data_to_process, model_type),
        )
    )

if (data_to_process == "test") | (data_to_process == "forward_val"):
    imputed_test.to_pickle(
        os.path.join(
            config["outputs"]["model_input_data_dir"],
            "{}_imputed_{}.pkl".format(data_to_process, model_type),
        )
    )
    not_imputed_test.to_pickle(
        os.path.join(
            config["outputs"]["model_input_data_dir"],
            "{}_not_imputed_{}.pkl".format(data_to_process, model_type),
        )
    )