-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatasetManager.py
175 lines (133 loc) · 9.2 KB
/
DatasetManager.py
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
import sys
import dataset_confs
import pandas as pd
import numpy as np
from sklearn.model_selection import StratifiedKFold
class DatasetManager:
def __init__(self, dataset_name):
self.dataset_name = dataset_name
self.case_id_col = dataset_confs.case_id_col[self.dataset_name]
self.activity_col = dataset_confs.activity_col[self.dataset_name]
self.timestamp_col = dataset_confs.timestamp_col[self.dataset_name]
self.label_col = dataset_confs.label_col[self.dataset_name]
self.pos_label = dataset_confs.pos_label[self.dataset_name]
self.dynamic_cat_cols = dataset_confs.dynamic_cat_cols[self.dataset_name]
self.static_cat_cols = dataset_confs.static_cat_cols[self.dataset_name]
self.dynamic_num_cols = dataset_confs.dynamic_num_cols[self.dataset_name]
self.static_num_cols = dataset_confs.static_num_cols[self.dataset_name]
self.sorting_cols = [self.timestamp_col, self.activity_col]
def read_dataset(self):
# read dataset
dtypes = {col:"object" for col in self.dynamic_cat_cols+self.static_cat_cols+[self.case_id_col, self.label_col, self.timestamp_col]}
for col in self.dynamic_num_cols + self.static_num_cols:
dtypes[col] = "float"
data = pd.read_csv(dataset_confs.filename[self.dataset_name], sep=";", dtype=dtypes)
data[self.timestamp_col] = pd.to_datetime(data[self.timestamp_col])
return data
def read_dataset_file(self,file):
print("It worked")
# read dataset
dtypes = {col:"object" for col in self.dynamic_cat_cols+self.static_cat_cols+[self.case_id_col, self.label_col, self.timestamp_col]}
for col in self.dynamic_num_cols + self.static_num_cols:
dtypes[col] = "float"
data = pd.read_csv(file, sep=";", dtype=dtypes)
data[self.timestamp_col] = pd.to_datetime(data[self.timestamp_col])
return data
def split_data(self, data, train_ratio, split="temporal", seed=22):
# split into train and test using temporal split
grouped = data.groupby(self.case_id_col)
start_timestamps = grouped[self.timestamp_col].min().reset_index()
if split == "temporal":
start_timestamps = start_timestamps.sort_values(self.timestamp_col, ascending=True, kind="mergesort")
elif split == "random":
np.random.seed(seed)
start_timestamps = start_timestamps.reindex(np.random.permutation(start_timestamps.index))
train_ids = list(start_timestamps[self.case_id_col])[:int(train_ratio*len(start_timestamps))]
train = data[data[self.case_id_col].isin(train_ids)].sort_values(self.timestamp_col, ascending=True, kind='mergesort')
test = data[~data[self.case_id_col].isin(train_ids)].sort_values(self.timestamp_col, ascending=True, kind='mergesort')
return (train, test)
def split_data_strict(self, data, train_ratio, split="temporal"):
# split into train and test using temporal split and discard events that overlap the periods
data = data.sort_values(self.sorting_cols, ascending=True, kind='mergesort')
grouped = data.groupby(self.case_id_col)
start_timestamps = grouped[self.timestamp_col].min().reset_index()
start_timestamps = start_timestamps.sort_values(self.timestamp_col, ascending=True, kind='mergesort')
train_ids = list(start_timestamps[self.case_id_col])[:int(train_ratio*len(start_timestamps))]
train = data[data[self.case_id_col].isin(train_ids)].sort_values(self.sorting_cols, ascending=True, kind='mergesort')
test = data[~data[self.case_id_col].isin(train_ids)].sort_values(self.sorting_cols, ascending=True, kind='mergesort')
split_ts = test[self.timestamp_col].min()
train = train[train[self.timestamp_col] < split_ts]
return (train, test)
def split_data_discard(self, data, train_ratio, split="temporal"):
# split into train and test using temporal split and discard events that overlap the periods
data = data.sort_values(self.sorting_cols, ascending=True, kind='mergesort')
grouped = data.groupby(self.case_id_col)
start_timestamps = grouped[self.timestamp_col].min().reset_index()
start_timestamps = start_timestamps.sort_values(self.timestamp_col, ascending=True, kind='mergesort')
train_ids = list(start_timestamps[self.case_id_col])[:int(train_ratio*len(start_timestamps))]
train = data[data[self.case_id_col].isin(train_ids)].sort_values(self.sorting_cols, ascending=True, kind='mergesort')
test = data[~data[self.case_id_col].isin(train_ids)].sort_values(self.sorting_cols, ascending=True, kind='mergesort')
split_ts = test[self.timestamp_col].min()
overlapping_cases = train[train[self.timestamp_col] >= split_ts][self.case_id_col].unique()
train = train[~train[self.case_id_col].isin(overlapping_cases)]
return (train, test)
def split_val(self, data, val_ratio, split="random", seed=22):
# split into train and test using temporal split
grouped = data.groupby(self.case_id_col)
start_timestamps = grouped[self.timestamp_col].min().reset_index()
if split == "temporal":
start_timestamps = start_timestamps.sort_values(self.timestamp_col, ascending=True, kind="mergesort")
elif split == "random":
np.random.seed(seed)
start_timestamps = start_timestamps.reindex(np.random.permutation(start_timestamps.index))
val_ids = list(start_timestamps[self.case_id_col])[-int(val_ratio*len(start_timestamps)):]
val = data[data[self.case_id_col].isin(val_ids)].sort_values(self.sorting_cols, ascending=True, kind="mergesort")
train = data[~data[self.case_id_col].isin(val_ids)].sort_values(self.sorting_cols, ascending=True, kind="mergesort")
return (train, val)
def generate_prefix_data(self, data, min_length, max_length):
# generate prefix data (each possible prefix becomes a trace)
data['case_length'] = data.groupby(self.case_id_col)[self.activity_col].transform(len)
dt_prefixes = data[data['case_length'] >= min_length].groupby(self.case_id_col).head(min_length)
dt_prefixes["prefix_nr"] = 1
dt_prefixes["orig_case_id"] = dt_prefixes[self.case_id_col]
for nr_events in range(min_length+1, max_length+1):
tmp = data[data['case_length'] >= nr_events].groupby(self.case_id_col).head(nr_events)
tmp["orig_case_id"] = tmp[self.case_id_col]
tmp[self.case_id_col] = tmp[self.case_id_col].apply(lambda x: "%s_%s"%(x, nr_events))
tmp["prefix_nr"] = nr_events
dt_prefixes = pd.concat([dt_prefixes, tmp], axis=0)
dt_prefixes['case_length'] = dt_prefixes['case_length'].apply(lambda x: min(max_length, x))
return dt_prefixes
def get_pos_case_length_quantile(self, data, quantile=0.90):
return int(np.ceil(data[data[self.label_col]==self.pos_label].groupby(self.case_id_col).size().quantile(quantile)))
def get_indexes(self, data):
return data.groupby(self.case_id_col).first().index
def get_relevant_data_by_indexes(self, data, indexes):
return data[data[self.case_id_col].isin(indexes)]
def get_label(self, data):
return data.groupby(self.case_id_col).first()[self.label_col]
def get_case_ids(self, data, nr_events=1):
case_ids = pd.Series(data.groupby(self.case_id_col).first().index)
if nr_events > 1:
case_ids = case_ids.apply(lambda x: "_".join(x.split("_")[:-1]))
return case_ids
def get_label_numeric(self, data):
y = self.get_label(data) # one row per case
return [1 if label == self.pos_label else 0 for label in y]
def get_class_ratio(self, data):
class_freqs = data[self.label_col].value_counts()
return class_freqs[self.pos_label] / class_freqs.sum()
def get_stratified_split_generator(self, data, n_splits=5, shuffle=True, random_state=22):
grouped_firsts = data.groupby(self.case_id_col, as_index=False).first()
skf = StratifiedKFold(n_splits=n_splits, shuffle=shuffle, random_state=random_state)
for train_index, test_index in skf.split(grouped_firsts, grouped_firsts[self.label_col]):
current_train_names = grouped_firsts[self.case_id_col][train_index]
train_chunk = data[data[self.case_id_col].isin(current_train_names)].sort_values(self.timestamp_col, ascending=True, kind='mergesort')
test_chunk = data[~data[self.case_id_col].isin(current_train_names)].sort_values(self.timestamp_col, ascending=True, kind='mergesort')
yield (train_chunk, test_chunk)
def get_idx_split_generator(self, dt_for_splitting, n_splits=5, shuffle=True, random_state=22):
skf = StratifiedKFold(n_splits=n_splits, shuffle=shuffle, random_state=random_state)
for train_index, test_index in skf.split(dt_for_splitting, dt_for_splitting[self.label_col]):
current_train_names = dt_for_splitting[self.case_id_col][train_index]
current_test_names = dt_for_splitting[self.case_id_col][test_index]
yield (current_train_names, current_test_names)