Shourya Bose commited on
Commit
927a2f5
·
1 Parent(s): eed52e7

upload datasets

Browse files
Files changed (3) hide show
  1. custom_dataset.py +1 -1
  2. custom_dataset_univariate.py +143 -0
  3. example.py +79 -0
custom_dataset.py CHANGED
@@ -93,7 +93,7 @@ def get_data_and_generate_train_val_test_sets(
93
  data_array: np.ndarray, # data matrix of shape (num_bldg,num_time_points,num_features). NOTE that features 2 and 3 are categorical features to embed time indices
94
  split_ratios: Union[List,Tuple], # 3-element list containing the ratios of train-val-test
95
  dataset_kwargs: Tuple # ONLY include num_bldg, lookback, lookahead, normalize, dtype, and transformer keys. See NRELComstock definition above for details.
96
- ):
97
 
98
  assert len(split_ratios) == 3, "The split list must contain three elements."
99
  assert all(isinstance(i, (int, float)) for i in split_ratios), "List contains non-numeric elements"
 
93
  data_array: np.ndarray, # data matrix of shape (num_bldg,num_time_points,num_features). NOTE that features 2 and 3 are categorical features to embed time indices
94
  split_ratios: Union[List,Tuple], # 3-element list containing the ratios of train-val-test
95
  dataset_kwargs: Tuple # ONLY include num_bldg, lookback, lookahead, normalize, dtype, and transformer keys. See NRELComstock definition above for details.
96
+ ) -> Tuple[torch.utils.data.Dataset, torch.utils.data.Dataset, torch.utils.data.Dataset, np.ndarray, np.ndarray]:
97
 
98
  assert len(split_ratios) == 3, "The split list must contain three elements."
99
  assert all(isinstance(i, (int, float)) for i in split_ratios), "List contains non-numeric elements"
custom_dataset_univariate.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.utils.data import Dataset
5
+ from typing import Union, List, Tuple, Dict
6
+
7
+ # written by Shourya Bose
8
+
9
+ class NRELComstock(Dataset):
10
+ """
11
+ torch Dataset class to load in data from numpy array
12
+ """
13
+
14
+ def __init__(
15
+ self,
16
+ data_array: np.ndarray, # numpy array of shape (B,L,F). B: number of buildings, L: number of time indices, F: number of features; keep F at 1 for the univariate case (this script)
17
+ num_bldg: int = 12, # number of buildings to consider, should not be greater than first dimension of data_array
18
+ lookback: int = 12, # forecasting lookback window
19
+ lookahead: int = 4, # forecasting lookahead window
20
+ normalize: bool = True, # whether to normalize feature-wise
21
+ dtype: torch.dtype = torch.float32, # data type of outputs
22
+ mean: np.ndarray = None, # if you want to supply your own statistics rather than calculate it in the function, do here. shape (1,1,F)
23
+ std: np.ndarray = None, # if you want to supply your own statistics rather than calculate it in the function, do here. shape (1,1,F)
24
+ transformer: bool = True # if normalize=True, this disables normalization of time indices for xformer embedding - unused for the univariate case (this script)
25
+ ):
26
+ super(NRELComstock, self).__init__()
27
+
28
+ if data_array.shape[0] < num_bldg:
29
+ raise ValueError('More buildings than present in file!')
30
+ else:
31
+ self.data = data_array[:num_bldg,:,[0]] # UNIVARIATE SELECTION: SELECT THE FIRST OUT OF 8 FEATURES
32
+ self.num_clients = num_bldg
33
+
34
+ # lookback and lookahead
35
+ self.lookback, self.lookahead = lookback, lookahead
36
+
37
+ # Calculate statistics
38
+ stacked = self.data.reshape(self.data.shape[0]*self.data.shape[1],self.data.shape[2])
39
+ if (mean is None) or (std is None): # statistics are not provided. Generate it from data
40
+ self.mean = stacked.mean(axis=0,keepdims=True)
41
+ self.std = stacked.std(axis=0,keepdims=True)
42
+ else: # statistics are provided. Use the provided statistics
43
+ self.mean = mean
44
+ self.std = std
45
+
46
+ # if transformer:
47
+ # # TRANSFORMER SPECIFIC: do not normalize date and time
48
+ # self.mean[0,1], self.std[0,1] = 0., 1.
49
+ # self.mean[0,2], self.std[0,2] = 0., 1.
50
+
51
+ self.ndata = (self.data-self.mean)/self.std # normalized data
52
+
53
+ # disambiguating between clients
54
+ len_per_client = self.data.shape[1] - lookback - lookahead + 1
55
+ self.total_len = len_per_client * self.num_clients
56
+ self.splits = np.array_split(np.arange(self.total_len),self.num_clients)
57
+
58
+ # save whether to normalize, and the data type
59
+ self.normalize = normalize
60
+ self.dtype = dtype
61
+
62
+ # if normalization is disabled, return to default statistics
63
+ if not self.normalize:
64
+ self.mean = np.zeros_like(self.mean)
65
+ self.std = np.ones_like(self.std)
66
+
67
+ def _client_and_idx(self, idx):
68
+
69
+ part_size = self.total_len // self.num_clients
70
+ part_index = idx // part_size
71
+ relative_position = idx % part_size
72
+
73
+ return relative_position, part_index
74
+
75
+ def __len__(self):
76
+
77
+ return self.total_len
78
+
79
+ def __getitem__(self, idx):
80
+
81
+ tidx, cidx = self._client_and_idx(idx)
82
+
83
+ if self.normalize:
84
+ x = self.ndata[cidx,tidx:tidx+self.lookback,0]
85
+ y = self.ndata[cidx,tidx+self.lookback:tidx+self.lookback+self.lookahead,0]
86
+ else:
87
+ x = self.data[cidx,tidx:tidx+self.lookback,0]
88
+ y = self.data[cidx,tidx+self.lookback:tidx+self.lookback+self.lookahead,0]
89
+
90
+ x, y = torch.tensor(x,dtype=self.dtype), torch.tensor(y,dtype=self.dtype)
91
+
92
+ return x,y
93
+
94
+
95
+ def get_data_and_generate_train_val_test_sets(
96
+ data_array: np.ndarray, # numpy array of shape (B,L,F). B: number of buildings, L: number of time indices, F: number of features; keep F at 1 for the univariate case (this script)
97
+ split_ratios: Union[List,Tuple], # 3-element list containing the non-negative ratios of train-val-test that add upto 1. for example, [0.8,0.1,0.1]
98
+ dataset_kwargs: Tuple # kwargs dictionary to pass into NRELComstock class, check definition. Do not pass data_array, mean, or std into it since this function does that
99
+ ) -> Tuple[torch.utils.data.Dataset, torch.utils.data.Dataset, torch.utils.data.Dataset, np.ndarray, np.ndarray]:
100
+ """
101
+ function to create three torch Dataset objects, each corresponding to train, validation, and test sets
102
+ """
103
+
104
+ assert len(split_ratios) == 3, "The split list must contain three elements."
105
+ assert all(isinstance(i, (int, float)) for i in split_ratios), "List contains non-numeric elements"
106
+ assert sum(split_ratios) <= 1, "Ratios must not sum upto more than 1."
107
+
108
+ cum_splits = np.cumsum(split_ratios)
109
+
110
+ train = data_array[:,:int(cum_splits[0]*data_array.shape[1]),:]
111
+ val = data_array[:,int(cum_splits[0]*data_array.shape[1]):int(cum_splits[1]*data_array.shape[1]),:]
112
+ test = data_array[:,int(cum_splits[1]*data_array.shape[1]):,:]
113
+
114
+ if 0 in train.shape:
115
+ train_set = None
116
+ raise ValueError("Train set is empty. Possibly empty data matrix or 0 ratio for train set has been input.")
117
+ else:
118
+ train_set = NRELComstock(
119
+ data_array = train,
120
+ **dataset_kwargs
121
+ )
122
+ mean, std = train_set.mean, train_set.std
123
+ if 0 in val.shape:
124
+ val_set = None
125
+ else:
126
+ val_set = NRELComstock(
127
+ data_array = val,
128
+ mean = mean,
129
+ std = std,
130
+ **dataset_kwargs
131
+ )
132
+ if 0 in test.shape:
133
+ test_set = None
134
+ else:
135
+ test_set = NRELComstock(
136
+ data_array = test,
137
+ mean = mean,
138
+ std = std,
139
+ **dataset_kwargs
140
+ )
141
+
142
+ # return the three datasets, as well as the statistics
143
+ return train_set, val_set, test_set, mean, std
example.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys
2
+ import torch
3
+ import numpy as np
4
+
5
+ # import the dataset generation functions
6
+ from custom_dataset import get_data_and_generate_train_val_test_sets as multivariate_dataset
7
+ from custom_dataset_univariate import get_data_and_generate_train_val_test_sets as univariate_dataset
8
+
9
+ # generate train-val-test datasets
10
+ # CASE 1: multivariate, with the time indices also normalized
11
+ train_1, val_1, test_1, mean_1, std_1 = multivariate_dataset(
12
+ data_array=np.load('./IllinoisHeterogenous.npz')['data'], # choose the appropriate file - homogenous or heterogenous
13
+ split_ratios=[0.8,0.1,0.1], # ratios that add up to 1 - the split is made along all buildings' time axis
14
+ dataset_kwargs={
15
+ 'num_bldg': np.load('./IllinoisHeterogenous.npz')['data'].shape[0],
16
+ 'lookback': 512,
17
+ 'lookahead': 48,
18
+ 'normalize': True,
19
+ 'dtype': torch.float32,
20
+ 'transformer': False # time indices are not normalized - use in non-Transformer scenarios where index embedding is not needed
21
+ }
22
+ )
23
+ # CASE 2: multivariate, with the time indices not normalized
24
+ train_2, val_2, test_2, mean_2, std_2 = multivariate_dataset(
25
+ data_array=np.load('./IllinoisHeterogenous.npz')['data'], # choose the appropriate file - homogenous or heterogenous
26
+ split_ratios=[0.8,0.1,0.1], # ratios that add up to 1 - the split is made along all buildings' time axis
27
+ dataset_kwargs={
28
+ 'num_bldg': np.load('./IllinoisHeterogenous.npz')['data'].shape[0],
29
+ 'lookback': 512,
30
+ 'lookahead': 48,
31
+ 'normalize': True,
32
+ 'dtype': torch.float32,
33
+ 'transformer': True # time indices are normalized - use in Transformer scenarios where index is embedded
34
+ }
35
+ )
36
+ # CASE 3: univariate
37
+ train_3, val_3, test_3, mean_3, std_3 = univariate_dataset(
38
+ data_array=np.load('./IllinoisHeterogenous.npz')['data'], # choose the appropriate file - homogenous or heterogenous
39
+ split_ratios=[0.8,0.1,0.1], # ratios that add up to 1 - the split is made along all buildings' time axis
40
+ dataset_kwargs={
41
+ 'num_bldg': np.load('./IllinoisHeterogenous.npz')['data'].shape[0],
42
+ 'lookback': 512,
43
+ 'lookahead': 48,
44
+ 'normalize': True,
45
+ 'dtype': torch.float32,
46
+ }
47
+ )
48
+
49
+
50
+ if __name__ == "__main__":
51
+
52
+ # Create dataloaders
53
+ dl_1 = torch.utils.data.DataLoader(train_1, batch_size=32, shuffle=False)
54
+ dl_2 = torch.utils.data.DataLoader(train_2, batch_size=32, shuffle=False)
55
+ dl_3 = torch.utils.data.DataLoader(train_3, batch_size=32, shuffle=False)
56
+
57
+ # print out of the shapes of elements in the first dataloader
58
+ for inp, label, future_time in dl_1:
59
+ print("Case 1: Each dataloader contains input, label, future_time. Here time indices are normalized.")
60
+ print(f"Input shape is (including batch size of 32): {inp.shape}.")
61
+ print(f"Label shape is (including batch size of 32): {label.shape}.")
62
+ print(f"Future time shape is (including batch size of 32): {future_time.shape}.")
63
+ break
64
+
65
+ # print out of the shapes of elements in the second dataloader
66
+ for inp, label, future_time in dl_2:
67
+ print("Case 2: Each dataloader contains input, label, future_time. Here time indices are not normalized to allow embedding.")
68
+ print(f"Input shape is (including batch size of 32): {inp.shape}.")
69
+ print(f"Label shape is (including batch size of 32): {label.shape}.")
70
+ print(f"Future time shape is (including batch size of 32): {future_time.shape}.")
71
+ break
72
+
73
+ # print out of the shapes of elements in the third dataloader
74
+ for inp, label in dl_3:
75
+ print("Case 3: Each dataloader contains input, label.")
76
+ print(f"Input shape is (including batch size of 32): {inp.shape}.")
77
+ print(f"Label shape is (including batch size of 32): {label.shape}.")
78
+ break
79
+