-
Notifications
You must be signed in to change notification settings - Fork 17
/
dataset_metrla.py
190 lines (164 loc) · 8.77 KB
/
dataset_metrla.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
import pickle
from torch.utils.data import DataLoader, Dataset
import pandas as pd
import numpy as np
import torch
import torchcde
from tqdm import tqdm
from utils import get_randmask, get_block_mask
import time
import os
os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE"
def get_mean_std():
df = pd.HDFStore("./data/metr_la/metr_la.h5").get('df')
data_len = len(df)
train_data = df[:int(data_len*0.7)].values
mean = np.mean(train_data, 0)
std = np.std(train_data, 0)
with open('./data/metr_la/metr_meanstd.pk', 'wb') as f:
pickle.dump((mean, std), f)
def sample_mask(shape, p=0.0015, p_noise=0.05, max_seq=1, min_seq=1, rng=None):
if rng is None:
rand = np.random.random
randint = np.random.randint
else:
rand = rng.random
randint = rng.integers
mask = rand(shape) < p
for col in range(mask.shape[1]):
idxs = np.flatnonzero(mask[:, col])
if not len(idxs):
continue
fault_len = min_seq
if max_seq > min_seq:
fault_len = fault_len + int(randint(max_seq - min_seq))
idxs_ext = np.concatenate([np.arange(i, i + fault_len) for i in idxs])
idxs = np.unique(idxs_ext)
idxs = np.clip(idxs, 0, shape[0] - 1)
mask[idxs, col] = True
mask = mask | (rand(mask.shape) < p_noise)
return mask.astype('uint8')
class MetrLA_Dataset(Dataset):
def __init__(self, eval_length=24, mode="train", val_len=0.1, test_len=0.2, missing_pattern='block',
is_interpolate=False, target_strategy='random', missing_ratio=None):
self.eval_length = eval_length
self.is_interpolate = is_interpolate
self.target_strategy = target_strategy
self.mode = mode
self.missing_ratio = missing_ratio
self.missing_pattern = missing_pattern
path = "./data/metr_la/metr_meanstd.pk"
with open(path, "rb") as f:
self.train_mean, self.train_std = pickle.load(f)
# create data for batch
self.use_index = []
self.cut_length = []
df = pd.read_hdf("./data/metr_la/metr_la.h5")
ob_mask = (df.values != 0.).astype('uint8')
SEED = 9101112
self.rng = np.random.default_rng(SEED)
if missing_pattern == 'block':
eval_mask = sample_mask(shape=(34272, 207), p=0.0015, p_noise=0.05, min_seq=12, max_seq=12 * 4, rng=self.rng)
if missing_ratio is not None:
eval_mask = sample_mask(shape=(34272, 207), p=missing_ratio, p_noise=0.05, min_seq=12, max_seq=12 * 4,
rng=self.rng)
elif missing_pattern == 'point':
eval_mask = sample_mask(shape=(34272, 207), p=0., p_noise=0.25, max_seq=12, min_seq=12 * 4, rng=self.rng)
gt_mask = (1-(eval_mask | (1-ob_mask))).astype('uint8')
val_start = int((1 - val_len - test_len) * len(df))
test_start = int((1 - test_len) * len(df))
c_data = (
(df.fillna(0).values - self.train_mean) / self.train_std
) * ob_mask
if mode == 'train':
self.observed_mask = ob_mask[:val_start]
self.gt_mask = gt_mask[:val_start]
self.observed_data = c_data[:val_start]
elif mode == 'valid':
self.observed_mask = ob_mask[val_start: test_start]
self.gt_mask = gt_mask[val_start: test_start]
self.observed_data = c_data[val_start: test_start]
elif mode == 'test':
self.observed_mask = ob_mask[test_start:]
self.gt_mask = gt_mask[test_start:]
self.observed_data = c_data[test_start:]
current_length = len(self.observed_mask) - eval_length + 1
if mode == "test":
n_sample = len(self.observed_data) // eval_length
c_index = np.arange(
0, 0 + eval_length * n_sample, eval_length
)
self.use_index += c_index.tolist()
self.cut_length += [0] * len(c_index)
if len(self.observed_data) % eval_length != 0:
self.use_index += [current_length - 1]
self.cut_length += [eval_length - len(self.observed_data) % eval_length]
elif mode != "test":
self.use_index = np.arange(current_length)
self.cut_length = [0] * len(self.use_index)
def __getitem__(self, org_index):
index = self.use_index[org_index]
ob_data = self.observed_data[index: index + self.eval_length]
ob_mask = self.observed_mask[index: index + self.eval_length]
ob_mask_t = torch.tensor(ob_mask).float()
gt_mask = self.gt_mask[index: index + self.eval_length]
if self.mode != 'train':
if self.mode == 'test' and self.missing_ratio is not None:
if self.missing_pattern == 'point':
gt_mask = get_test_randmask(torch.tensor(ob_mask).to(torch.float32), missing_ratio=self.missing_ratio).numpy()
cond_mask = torch.tensor(gt_mask).to(torch.float32)
else:
if self.target_strategy != 'random':
cond_mask = get_block_mask(ob_mask_t, target_strategy=self.target_strategy)
else:
cond_mask = get_randmask(ob_mask_t)
s = {
"observed_data": ob_data,
"observed_mask": ob_mask,
"gt_mask": gt_mask,
"timepoints": np.arange(self.eval_length),
"cut_length": self.cut_length[org_index],
"cond_mask": cond_mask.numpy()
}
if self.is_interpolate:
tmp_data = torch.tensor(ob_data).to(torch.float64)
itp_data = torch.where(cond_mask == 0, float('nan'), tmp_data).to(torch.float32)
itp_data = torchcde.linear_interpolation_coeffs(itp_data.permute(1, 0).unsqueeze(-1)).squeeze(-1).permute(1, 0)
s["coeffs"] = itp_data.numpy()
return s
def __len__(self):
return len(self.use_index)
def get_dataloader(batch_size, device, val_len=0.1, test_len=0.2, missing_pattern='block',
is_interpolate=False, num_workers=4, target_strategy='random'):
dataset = MetrLA_Dataset(mode="train", val_len=val_len, test_len=test_len, missing_pattern=missing_pattern,
is_interpolate=is_interpolate, target_strategy=target_strategy)
train_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=True)
dataset_test = MetrLA_Dataset(mode="test", val_len=val_len, test_len=test_len, missing_pattern=missing_pattern,
is_interpolate=is_interpolate, target_strategy=target_strategy)
test_loader = DataLoader(dataset_test, batch_size=batch_size, num_workers=num_workers, shuffle=False)
dataset_valid = MetrLA_Dataset(mode="valid", val_len=val_len, test_len=test_len, missing_pattern=missing_pattern,
is_interpolate=is_interpolate, target_strategy=target_strategy)
valid_loader = DataLoader(dataset_valid, batch_size=batch_size, num_workers=num_workers, shuffle=False)
scaler = torch.from_numpy(dataset.train_std).to(device).float()
mean_scaler = torch.from_numpy(dataset.train_mean).to(device).float()
return train_loader, valid_loader, test_loader, scaler, mean_scaler
def get_test_dataloader(batch_size, device, val_len=0.1, test_len=0.2, missing_pattern='block',
is_interpolate=False, num_workers=4, target_strategy='random', is_pcc_itp=False, missing_ratio=None):
dataset = MetrLA_Dataset(mode="train", val_len=val_len, test_len=test_len, missing_pattern=missing_pattern,
is_interpolate=is_interpolate, target_strategy=target_strategy)
dataset_test = MetrLA_Dataset(mode="test", val_len=val_len, test_len=test_len, missing_pattern=missing_pattern,
is_interpolate=is_interpolate, target_strategy=target_strategy,
missing_ratio=missing_ratio)
test_loader = DataLoader(dataset_test, batch_size=batch_size, num_workers=num_workers, shuffle=False)
scaler = torch.from_numpy(dataset.train_std).to(device).float()
mean_scaler = torch.from_numpy(dataset.train_mean).to(device).float()
return test_loader, scaler, mean_scaler
def get_test_randmask(observed_mask, missing_ratio):
rand_for_mask = torch.rand_like(observed_mask) * observed_mask
rand_for_mask = rand_for_mask.reshape(-1)
sample_ratio = missing_ratio # missing ratio
num_observed = observed_mask.sum().item()
num_masked = round(num_observed * sample_ratio)
rand_for_mask[rand_for_mask.topk(num_masked).indices] = -1
cond_mask = (rand_for_mask > 0).reshape(observed_mask.shape).float()
return cond_mask