-
Notifications
You must be signed in to change notification settings - Fork 0
/
datautils.py
238 lines (202 loc) · 8.31 KB
/
datautils.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
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
import os
import numpy as np
import pandas as pd
import math
import random
from datetime import datetime
import pickle
from utils import pkl_load, pad_nan_to_target, data_dropout
from scipy.io.arff import loadarff
from sklearn.preprocessing import StandardScaler, MinMaxScaler
import h5py
datasets_folder = 'datasets'
def load_UCR(dataset, irregular):
train_file = os.path.join(datasets_folder, 'UCR', dataset, dataset + "_TRAIN.tsv")
test_file = os.path.join(datasets_folder, 'UCR', dataset, dataset + "_TEST.tsv")
train_df = pd.read_csv(train_file, sep='\t', header=None)
test_df = pd.read_csv(test_file, sep='\t', header=None)
train_array = np.array(train_df)
test_array = np.array(test_df)
# Move the labels to {0, ..., L-1}
labels = np.unique(train_array[:, 0])
transform = {}
for i, l in enumerate(labels):
transform[l] = i
train = train_array[:, 1:].astype(np.float64)
train_labels = np.vectorize(transform.get)(train_array[:, 0])
test = test_array[:, 1:].astype(np.float64)
test_labels = np.vectorize(transform.get)(test_array[:, 0])
#vary init 0 to nan value
if dataset in ['PickupGestureWiimoteZ']:
train_nan = np.isnan(train)
train[train_nan] = 0
test_nan = np.isnan(test)
test[test_nan] = 0
print('train & test :nan -> 0')
# Normalization for non-normalized datasets
# To keep the amplitude information, we do not normalize values over
# individual time series, but on the whole dataset
if dataset not in [
'AllGestureWiimoteX',
'AllGestureWiimoteY',
'AllGestureWiimoteZ',
'BME',
'Chinatown',
'Crop',
'EOGHorizontalSignal',
'EOGVerticalSignal',
'Fungi',
'GestureMidAirD1',
'GestureMidAirD2',
'GestureMidAirD3',
'GesturePebbleZ1',
'GesturePebbleZ2',
'GunPointAgeSpan',
'GunPointMaleVersusFemale',
'GunPointOldVersusYoung',
'HouseTwenty',
'InsectEPGRegularTrain',
'InsectEPGSmallTrain',
'MelbournePedestrian',
'PickupGestureWiimoteZ',
'PigAirwayPressure',
'PigArtPressure',
'PigCVP',
'PLAID',
'PowerCons',
'Rock',
'SemgHandGenderCh2',
'SemgHandMovementCh2',
'SemgHandSubjectCh2',
'ShakeGestureWiimoteZ',
'SmoothSubspace',
'UMD'
]:
return train[..., np.newaxis], train_labels, test[..., np.newaxis], test_labels
mean = np.nanmean(train)
std = np.nanstd(train)
train = (train - mean) / std
test = (test - mean) / std
train_data = train[..., np.newaxis]
test_data = test[..., np.newaxis]
if irregular > 0:
train_data, _ = data_dropout(train_data, irregular)
test_data , _ = data_dropout(test_data, irregular)
return train_data, train_labels, test_data, test_labels
def load_UEA(dataset, irregular):
train_data = loadarff(f'{datasets_folder}/UEA/{dataset}/{dataset}_TRAIN.arff')[0]
test_data = loadarff(f'{datasets_folder}/UEA/{dataset}/{dataset}_TEST.arff')[0]
def extract_data(data):
res_data = []
res_labels = []
for t_data, t_label in data:
t_data = np.array([ d.tolist() for d in t_data ])
t_label = t_label.decode("utf-8")
res_data.append(t_data)
res_labels.append(t_label)
return np.array(res_data).swapaxes(1, 2), np.array(res_labels)
train_X, train_y = extract_data(train_data)
test_X, test_y = extract_data(test_data)
scaler = StandardScaler()
scaler.fit(train_X.reshape(-1, train_X.shape[-1]))
train_X = scaler.transform(train_X.reshape(-1, train_X.shape[-1])).reshape(train_X.shape)
test_X = scaler.transform(test_X.reshape(-1, test_X.shape[-1])).reshape(test_X.shape)
labels = np.unique(train_y)
transform = { k : i for i, k in enumerate(labels)}
train_y = np.vectorize(transform.get)(train_y)
test_y = np.vectorize(transform.get)(test_y)
if irregular > 0:
train_X, _ = data_dropout(train_X, irregular)
test_X , _ = data_dropout(test_X, irregular)
return train_X, train_y, test_X, test_y
def _get_time_features(dt):
return np.stack([
dt.minute.to_numpy(),
dt.hour.to_numpy(),
dt.dayofweek.to_numpy(),
dt.day.to_numpy(),
dt.dayofyear.to_numpy(),
dt.month.to_numpy(),
dt.weekofyear.to_numpy(),
], axis=1).astype(np.float)
def load_forecast_hdf(name, univar=False):
h5_path = f'{datasets_folder}/{name}.h5'
data = pd.read_hdf(h5_path)
data = data.to_numpy()
print('raw data:',data.shape)
train_slice = slice(None, int(0.6 * len(data)))
valid_slice = slice(int(0.6 * len(data)), int(0.8 * len(data)))
test_slice = slice(int(0.8 * len(data)), None)
scaler = StandardScaler().fit(data[train_slice]) #[T,N] or [T,F]
data = scaler.transform(data)
if name in ('exchange-rate','wind'):
data = np.expand_dims(data.T, -1) # Each variable is an instance rather than a feature #[N,T,1]
print("data shape:",data.shape)
else:
data = np.expand_dims(data, 0)
n_covariate_cols = 0 # Do not use date information
if n_covariate_cols > 0:
dt_scaler = StandardScaler().fit(dt_embed[train_slice])
dt_embed = np.expand_dims(dt_scaler.transform(dt_embed), 0)
data = np.concatenate([np.repeat(dt_embed, data.shape[0], axis=0), data], axis=-1)
pred_lens = [48, 96 ,128, 168, 192, 288, 336, 672]
padding = 200
return data, train_slice, valid_slice, test_slice, scaler, pred_lens, n_covariate_cols, padding
def load_forecast_csv(name, univar=False):
data = pd.read_csv(f'{datasets_folder}/{name}.csv', index_col='date', parse_dates=True)
dt_embed = _get_time_features(data.index)
n_covariate_cols = dt_embed.shape[-1]
if univar:
if name == 'WTH':
data = data[['WetBulbCelsius']]
else:
data = data.iloc[:, -1:]
data = data.to_numpy()
if name == 'ILI':
train_slice = slice(None, int(0.7 * len(data)))
valid_slice = slice(int(0.7 * len(data)), int(0.8 * len(data)))
test_slice = slice(int(0.8 * len(data)), None)
else:
train_slice = slice(None, int(0.6 * len(data)))
valid_slice = slice(int(0.6 * len(data)), int(0.8 * len(data)))
test_slice = slice(int(0.8 * len(data)), None)
scaler = StandardScaler().fit(data[train_slice])
data = scaler.transform(data)
# if name in ():
# data = np.expand_dims(data.T, -1) # Each variable is an instance rather than a feature
# else:
data = np.expand_dims(data, 0)
n_covariate_cols = 0 # Do not use date information
if n_covariate_cols > 0:
dt_scaler = StandardScaler().fit(dt_embed[train_slice])
dt_embed = np.expand_dims(dt_scaler.transform(dt_embed), 0)
data = np.concatenate([np.repeat(dt_embed, data.shape[0], axis=0), data], axis=-1)
if name in ('ILI'):
pred_lens = [3, 6, 12, 48, 60, 72]
padding = 100
else:
pred_lens =[48, 96 ,128, 168, 192, 288, 336, 672]
padding = 200
return data, train_slice, valid_slice, test_slice, scaler, pred_lens, n_covariate_cols, padding
def load_imputation(name, irregular):
data = pd.read_csv(f'{datasets_folder}/{name}.csv', index_col='date', parse_dates=True)
data = data.to_numpy()
print('raw data:',data.shape)
if name == 'ETTh1' or name == 'ETTh2':
train_slice = slice(None, 12*30*24)
valid_slice = slice(12*30*24, 16*30*24)
test_slice = slice(16*30*24, 20*30*24)
elif name == 'ETTm1' or name == 'ETTm2':
train_slice = slice(None, 12*30*24*4)
valid_slice = slice(12*30*24*4, 16*30*24*4)
test_slice = slice(16*30*24*4, 20*30*24*4)
else:
train_slice = slice(None, int(0.7 * len(data)))
valid_slice = slice(int(0.7 * len(data)), int(0.8 * len(data)))
test_slice = slice(int(0.8 * len(data)), None)
scaler = StandardScaler().fit(data[train_slice])
data = scaler.transform(data)
data = np.expand_dims(data, 0)
missing_data, missing_mask = data_dropout(data, irregular)
lens = 96
return data, missing_data, missing_mask, train_slice, valid_slice, test_slice, scaler, lens