|
a |
|
b/formulate_problem.py |
|
|
1 |
import pandas as pd |
|
|
2 |
import numpy as np |
|
|
3 |
|
|
|
4 |
|
|
|
5 |
def get_splits(age_at_exam, patient_ids, exam_ids, splits, min_age_valid=16, max_age_valid=85, seed=0): |
|
|
6 |
rng = np.random.RandomState(seed) |
|
|
7 |
if sum(splits) > 1.0: |
|
|
8 |
raise ValueError('splits should be sum to a number smaller than one.') |
|
|
9 |
n_exams = len(exam_ids) |
|
|
10 |
# Get patients |
|
|
11 |
patients = np.unique(patient_ids) |
|
|
12 |
n_patients = len(patients) |
|
|
13 |
# Create correspondence |
|
|
14 |
hash_exams = dict(zip(exam_ids, range(n_exams))) |
|
|
15 |
hash_patients = dict(zip(patients, range(n_patients))) |
|
|
16 |
inverse_hash_patients = dict(zip(range(n_patients), patients)) |
|
|
17 |
# Get all exams for each patient |
|
|
18 |
patient_exams = [[] for _ in range(n_patients)] |
|
|
19 |
for exam_idx in range(n_exams): |
|
|
20 |
exam_id = exam_ids[exam_idx] |
|
|
21 |
patient_id = patient_ids[exam_idx] |
|
|
22 |
patient_idx = hash_patients[patient_id] |
|
|
23 |
patient_exams[patient_idx].append(exam_id) |
|
|
24 |
|
|
|
25 |
# Get the age at one of the exams for each patient |
|
|
26 |
ages, _, _ = np.unique(age_at_exam, return_inverse=True, return_counts=True) |
|
|
27 |
patient_idx_per_age = {a: [] for a in ages} |
|
|
28 |
patient_single_exam = np.zeros(n_patients, dtype=int) |
|
|
29 |
for patient_idx in range(n_patients): |
|
|
30 |
# Pick random exam id for the given patient |
|
|
31 |
# OBS:Another formulation that could make sense could be to always pick the first exam.... |
|
|
32 |
id_exam = rng.choice(patient_exams[patient_idx]) |
|
|
33 |
patient_single_exam[patient_idx] = id_exam |
|
|
34 |
exam_idx = hash_exams[id_exam] |
|
|
35 |
a = age_at_exam[exam_idx] |
|
|
36 |
patient_idx_per_age[a].append(patient_idx) |
|
|
37 |
|
|
|
38 |
# Get number of patient in each split |
|
|
39 |
n_splits = [int(np.floor(s * n_patients)) for s in splits] |
|
|
40 |
n_splits += [n_patients - sum(n_splits)] |
|
|
41 |
# Shuffle |
|
|
42 |
rng.shuffle(ages) # Shuffle ages |
|
|
43 |
for a, patient_idx in patient_idx_per_age.items(): # Shuffle within the same age |
|
|
44 |
rng.shuffle(patient_idx) |
|
|
45 |
# Pick one id per age and build a list from that |
|
|
46 |
all_patient_idx = [] |
|
|
47 |
stop = False |
|
|
48 |
# Pick ids within the given range first (which will probably be used for training, validation and test) |
|
|
49 |
while not stop: |
|
|
50 |
stop = True |
|
|
51 |
for a in ages[(ages >= min_age_valid) & (ages <= max_age_valid)]: |
|
|
52 |
if patient_idx_per_age[a]: |
|
|
53 |
patient_idx = patient_idx_per_age[a].pop() |
|
|
54 |
all_patient_idx.append(patient_idx) |
|
|
55 |
stop = False |
|
|
56 |
# Pick remaining ids last (which will probably be used only for training) |
|
|
57 |
stop = False |
|
|
58 |
while not stop: |
|
|
59 |
stop = True |
|
|
60 |
for a in ages[(ages < min_age_valid) | (ages > max_age_valid)]: |
|
|
61 |
if patient_idx_per_age[a]: |
|
|
62 |
patient_idx = patient_idx_per_age[a].pop() |
|
|
63 |
all_patient_idx.append(patient_idx) |
|
|
64 |
stop = False |
|
|
65 |
# Save ids |
|
|
66 |
patients_in_splits = [[] for n in n_splits] |
|
|
67 |
single_exam_in_split = [[] for n in n_splits] |
|
|
68 |
exams_in_splits = [[] for n in n_splits] |
|
|
69 |
for i, patient_idx in enumerate(all_patient_idx): |
|
|
70 |
last_n = 0 |
|
|
71 |
for s, n in enumerate(np.cumsum(n_splits)): |
|
|
72 |
if last_n <= i < n: |
|
|
73 |
patients_in_splits[s].append(inverse_hash_patients[patient_idx]) |
|
|
74 |
single_exam_in_split[s].append(patient_single_exam[patient_idx]) |
|
|
75 |
exams_in_splits[s] += patient_exams[patient_idx] |
|
|
76 |
last_n = n |
|
|
77 |
|
|
|
78 |
return patients_in_splits, single_exam_in_split, exams_in_splits |
|
|
79 |
|
|
|
80 |
|
|
|
81 |
if __name__ == "__main__": |
|
|
82 |
import argparse |
|
|
83 |
import warnings |
|
|
84 |
|
|
|
85 |
parser = argparse.ArgumentParser(description='Generate data summary for the age prediction problem') |
|
|
86 |
parser.add_argument('file', |
|
|
87 |
help='csv file to read data from.') |
|
|
88 |
parser.add_argument('--exam_id_col', default='N_exame', |
|
|
89 |
help='column in csv containing exam id') |
|
|
90 |
parser.add_argument('--age_col', default='Idade', |
|
|
91 |
help='column in csv containing age') |
|
|
92 |
parser.add_argument('--patient_id_col', default='N_paciente_univoco', |
|
|
93 |
help='column in csv containing patient id') |
|
|
94 |
parser.add_argument('--splits', default=[0.15, 0.05], nargs='*', type=float, |
|
|
95 |
help='percentage of data in each split') |
|
|
96 |
parser.add_argument('--splits_names', default=['test', 'val', 'train'], nargs='*', type=str, |
|
|
97 |
help='split names') |
|
|
98 |
parser.add_argument('--no_plot', action='store_true', |
|
|
99 |
help='dont show plots') |
|
|
100 |
args, unk = parser.parse_known_args() |
|
|
101 |
if unk: |
|
|
102 |
warnings.warn("Unknown arguments:" + str(unk) + ".") |
|
|
103 |
|
|
|
104 |
# Open csv file |
|
|
105 |
df = pd.read_csv(args.file, low_memory=False) |
|
|
106 |
# Remove duplicated rows |
|
|
107 |
df.drop_duplicates(args.exam_id_col, inplace=True) |
|
|
108 |
# Get ids from csv file |
|
|
109 |
exam_ids = np.array(df[args.exam_id_col], dtype=int) |
|
|
110 |
age_at_exam = np.array(df[args.age_col]) |
|
|
111 |
patient_ids = np.array(df[args.patient_id_col], dtype=int) |
|
|
112 |
# define splits |
|
|
113 |
patients_in_splits, single_exam_in_split, exams_in_splits = get_splits(age_at_exam, patient_ids, exam_ids, args.splits) |
|
|
114 |
|
|
|
115 |
if not args.no_plot: |
|
|
116 |
import seaborn as sns |
|
|
117 |
import matplotlib.pyplot as plt |
|
|
118 |
n = len(args.splits) + 1 |
|
|
119 |
fig, ax = plt.subplots(nrows=n) |
|
|
120 |
for i in range(n): |
|
|
121 |
age_single_exam = age_at_exam[np.isin(exam_ids, single_exam_in_split[i])] |
|
|
122 |
age = age_at_exam[np.isin(exam_ids, exams_in_splits[i])] |
|
|
123 |
sns.histplot(age, ax=ax[i], kde=False, bins=range(0, 130, 1)) |
|
|
124 |
sns.histplot(age_single_exam, ax=ax[i], kde=False, bins=range(0, 130, 1)) |
|
|
125 |
plt.show() |
|
|
126 |
|