-
Notifications
You must be signed in to change notification settings - Fork 157
/
prepareData.py
303 lines (254 loc) · 11.6 KB
/
prepareData.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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import os
import numpy as np
import argparse
import configparser
def search_data(sequence_length, num_of_depend, label_start_idx,
num_for_predict, units, points_per_hour):
'''
Parameters
----------
sequence_length: int, length of all history data
num_of_depend: int,
label_start_idx: int, the first index of predicting target
num_for_predict: int, the number of points will be predicted for each sample
units: int, week: 7 * 24, day: 24, recent(hour): 1
points_per_hour: int, number of points per hour, depends on data
Returns
----------
list[(start_idx, end_idx)]
'''
if points_per_hour < 0:
raise ValueError("points_per_hour should be greater than 0!")
if label_start_idx + num_for_predict > sequence_length:
return None
x_idx = []
for i in range(1, num_of_depend + 1):
start_idx = label_start_idx - points_per_hour * units * i
end_idx = start_idx + num_for_predict
if start_idx >= 0:
x_idx.append((start_idx, end_idx))
else:
return None
if len(x_idx) != num_of_depend:
return None
return x_idx[::-1]
def get_sample_indices(data_sequence, num_of_weeks, num_of_days, num_of_hours,
label_start_idx, num_for_predict, points_per_hour=12):
'''
Parameters
----------
data_sequence: np.ndarray
shape is (sequence_length, num_of_vertices, num_of_features)
num_of_weeks, num_of_days, num_of_hours: int
label_start_idx: int, the first index of predicting target, 预测值开始的那个点
num_for_predict: int,
the number of points will be predicted for each sample
points_per_hour: int, default 12, number of points per hour
Returns
----------
week_sample: np.ndarray
shape is (num_of_weeks * points_per_hour,
num_of_vertices, num_of_features)
day_sample: np.ndarray
shape is (num_of_days * points_per_hour,
num_of_vertices, num_of_features)
hour_sample: np.ndarray
shape is (num_of_hours * points_per_hour,
num_of_vertices, num_of_features)
target: np.ndarray
shape is (num_for_predict, num_of_vertices, num_of_features)
'''
week_sample, day_sample, hour_sample = None, None, None
if label_start_idx + num_for_predict > data_sequence.shape[0]:
return week_sample, day_sample, hour_sample, None
if num_of_weeks > 0:
week_indices = search_data(data_sequence.shape[0], num_of_weeks,
label_start_idx, num_for_predict,
7 * 24, points_per_hour)
if not week_indices:
return None, None, None, None
week_sample = np.concatenate([data_sequence[i: j]
for i, j in week_indices], axis=0)
if num_of_days > 0:
day_indices = search_data(data_sequence.shape[0], num_of_days,
label_start_idx, num_for_predict,
24, points_per_hour)
if not day_indices:
return None, None, None, None
day_sample = np.concatenate([data_sequence[i: j]
for i, j in day_indices], axis=0)
if num_of_hours > 0:
hour_indices = search_data(data_sequence.shape[0], num_of_hours,
label_start_idx, num_for_predict,
1, points_per_hour)
if not hour_indices:
return None, None, None, None
hour_sample = np.concatenate([data_sequence[i: j]
for i, j in hour_indices], axis=0)
target = data_sequence[label_start_idx: label_start_idx + num_for_predict]
return week_sample, day_sample, hour_sample, target
def read_and_generate_dataset(graph_signal_matrix_filename,
num_of_weeks, num_of_days,
num_of_hours, num_for_predict,
points_per_hour=12, save=False):
'''
Parameters
----------
graph_signal_matrix_filename: str, path of graph signal matrix file
num_of_weeks, num_of_days, num_of_hours: int
num_for_predict: int
points_per_hour: int, default 12, depends on data
Returns
----------
feature: np.ndarray,
shape is (num_of_samples, num_of_depend * points_per_hour,
num_of_vertices, num_of_features)
target: np.ndarray,
shape is (num_of_samples, num_of_vertices, num_for_predict)
'''
data_seq = np.load(graph_signal_matrix_filename)['data'] # (sequence_length, num_of_vertices, num_of_features)
all_samples = []
for idx in range(data_seq.shape[0]):
sample = get_sample_indices(data_seq, num_of_weeks, num_of_days,
num_of_hours, idx, num_for_predict,
points_per_hour)
if ((sample[0] is None) and (sample[1] is None) and (sample[2] is None)):
continue
week_sample, day_sample, hour_sample, target = sample
sample = [] # [(week_sample),(day_sample),(hour_sample),target,time_sample]
if num_of_weeks > 0:
week_sample = np.expand_dims(week_sample, axis=0).transpose((0, 2, 3, 1)) # (1,N,F,T)
sample.append(week_sample)
if num_of_days > 0:
day_sample = np.expand_dims(day_sample, axis=0).transpose((0, 2, 3, 1)) # (1,N,F,T)
sample.append(day_sample)
if num_of_hours > 0:
hour_sample = np.expand_dims(hour_sample, axis=0).transpose((0, 2, 3, 1)) # (1,N,F,T)
sample.append(hour_sample)
target = np.expand_dims(target, axis=0).transpose((0, 2, 3, 1))[:, :, 0, :] # (1,N,T)
sample.append(target)
time_sample = np.expand_dims(np.array([idx]), axis=0) # (1,1)
sample.append(time_sample)
all_samples.append(
sample) # sampe:[(week_sample),(day_sample),(hour_sample),target,time_sample] = [(1,N,F,Tw),(1,N,F,Td),(1,N,F,Th),(1,N,Tpre),(1,1)]
split_line1 = int(len(all_samples) * 0.6)
split_line2 = int(len(all_samples) * 0.8)
training_set = [np.concatenate(i, axis=0)
for i in zip(*all_samples[:split_line1])] # [(B,N,F,Tw),(B,N,F,Td),(B,N,F,Th),(B,N,Tpre),(B,1)]
validation_set = [np.concatenate(i, axis=0)
for i in zip(*all_samples[split_line1: split_line2])]
testing_set = [np.concatenate(i, axis=0)
for i in zip(*all_samples[split_line2:])]
train_x = np.concatenate(training_set[:-2], axis=-1) # (B,N,F,T')
val_x = np.concatenate(validation_set[:-2], axis=-1)
test_x = np.concatenate(testing_set[:-2], axis=-1)
train_target = training_set[-2] # (B,N,T)
val_target = validation_set[-2]
test_target = testing_set[-2]
train_timestamp = training_set[-1] # (B,1)
val_timestamp = validation_set[-1]
test_timestamp = testing_set[-1]
(stats, train_x_norm, val_x_norm, test_x_norm) = normalization(train_x, val_x, test_x)
all_data = {
'train': {
'x': train_x_norm,
'target': train_target,
'timestamp': train_timestamp,
},
'val': {
'x': val_x_norm,
'target': val_target,
'timestamp': val_timestamp,
},
'test': {
'x': test_x_norm,
'target': test_target,
'timestamp': test_timestamp,
},
'stats': {
'_mean': stats['_mean'],
'_std': stats['_std'],
}
}
print('train x:', all_data['train']['x'].shape)
print('train target:', all_data['train']['target'].shape)
print('train timestamp:', all_data['train']['timestamp'].shape)
print()
print('val x:', all_data['val']['x'].shape)
print('val target:', all_data['val']['target'].shape)
print('val timestamp:', all_data['val']['timestamp'].shape)
print()
print('test x:', all_data['test']['x'].shape)
print('test target:', all_data['test']['target'].shape)
print('test timestamp:', all_data['test']['timestamp'].shape)
print()
print('train data _mean :', stats['_mean'].shape, stats['_mean'])
print('train data _std :', stats['_std'].shape, stats['_std'])
if save:
file = os.path.basename(graph_signal_matrix_filename).split('.')[0]
dirpath = os.path.dirname(graph_signal_matrix_filename)
filename = os.path.join(dirpath, file + '_r' + str(num_of_hours) + '_d' + str(num_of_days) + '_w' + str(num_of_weeks)) + '_astcgn'
print('save file:', filename)
np.savez_compressed(filename,
train_x=all_data['train']['x'], train_target=all_data['train']['target'],
train_timestamp=all_data['train']['timestamp'],
val_x=all_data['val']['x'], val_target=all_data['val']['target'],
val_timestamp=all_data['val']['timestamp'],
test_x=all_data['test']['x'], test_target=all_data['test']['target'],
test_timestamp=all_data['test']['timestamp'],
mean=all_data['stats']['_mean'], std=all_data['stats']['_std']
)
return all_data
def normalization(train, val, test):
'''
Parameters
----------
train, val, test: np.ndarray (B,N,F,T)
Returns
----------
stats: dict, two keys: mean and std
train_norm, val_norm, test_norm: np.ndarray,
shape is the same as original
'''
assert train.shape[1:] == val.shape[1:] and val.shape[1:] == test.shape[1:] # ensure the num of nodes is the same
mean = train.mean(axis=(0,1,3), keepdims=True)
std = train.std(axis=(0,1,3), keepdims=True)
print('mean.shape:',mean.shape)
print('std.shape:',std.shape)
def normalize(x):
return (x - mean) / std
train_norm = normalize(train)
val_norm = normalize(val)
test_norm = normalize(test)
return {'_mean': mean, '_std': std}, train_norm, val_norm, test_norm
# prepare dataset
parser = argparse.ArgumentParser()
parser.add_argument("--config", default='configurations/METR_LA_astgcn.conf', type=str,
help="configuration file path")
args = parser.parse_args()
config = configparser.ConfigParser()
print('Read configuration file: %s' % (args.config))
config.read(args.config)
data_config = config['Data']
training_config = config['Training']
adj_filename = data_config['adj_filename']
graph_signal_matrix_filename = data_config['graph_signal_matrix_filename']
if config.has_option('Data', 'id_filename'):
id_filename = data_config['id_filename']
else:
id_filename = None
num_of_vertices = int(data_config['num_of_vertices'])
points_per_hour = int(data_config['points_per_hour'])
num_for_predict = int(data_config['num_for_predict'])
len_input = int(data_config['len_input'])
dataset_name = data_config['dataset_name']
num_of_weeks = int(training_config['num_of_weeks'])
num_of_days = int(training_config['num_of_days'])
num_of_hours = int(training_config['num_of_hours'])
num_of_vertices = int(data_config['num_of_vertices'])
points_per_hour = int(data_config['points_per_hour'])
num_for_predict = int(data_config['num_for_predict'])
graph_signal_matrix_filename = data_config['graph_signal_matrix_filename']
data = np.load(graph_signal_matrix_filename)
data['data'].shape
all_data = read_and_generate_dataset(graph_signal_matrix_filename, 0, 0, num_of_hours, num_for_predict, points_per_hour=points_per_hour, save=True)